1

I've been trying to generate a pattern of circles using a for loop. However, when it runs everything looks fine except for the 9th ring of circles which is ever so slightly. Having looked at a print out of numbers for that circle everything looks fine, so I can't work out what is going wrong. However, when I add one to the angle value of that ring. i.e. j (the commented out code) it pretty much corrects.

Any idea why this might happen. having looked at all the numbers I can only think it is some math error that I haven't factored in or am I missing something obvious.

Thanks!

ocd trigger warning

          ellipse(325,325,15,15);      
          float div = 1;
          for (int i = i; i < 25; i++)
          {
            div = i*6
            float segment = 360/div;
            float radius = (i*20);
            for (int j = 0; j < 360; j+=segment)
            {
              //if (i==8)
              //{
                //println("before " + j);
                //j+=1;
                //println("after " + j);
              //}
              float x = 325 + (radius*cos(radians(j)));
              float y = 325 + (radius*sin(radians(j)));
              ellipse(x, y, 15, 15);
            }
          }
4

3 回答 3

2

好的,三件事,按重要性排序。其中两个已经被提及。

1) 清除ints。变量i可以是int,但不能是其他变量(特别是j因为它是角度,而不是计数器或索引),并且您要确保所有数学运算都将数字视为doubles。甚至将您的常量指定为doubles(例如,使用1d而不是1)。

2) 避免累积误差。在您的内部for循环中,您反复添加到j. 坏的。相反,直接根据您正在计算的圆计算您的角度。

3)使用double,而不是float。你会得到更好的精度。

我会这样做...

ellipse(325,325,15,15);      
for (int i = i; i < 25; i++)
{
  double div = i*6d;
  double radius = (i*20d);
  for (int j = 0; j < div; j++)
  {
    double theta = j * 360d / div;
    double x = 325d + (radius*cos(radians(theta)));
    double y = 325d + (radius*sin(radians(theta)));
    ellipse(x, y, 15, 15);
  }
}
于 2013-09-23T00:37:18.303 回答
2

你得到segmentas a float,然后你使用 anint来计算度数。

for (int j=0; j < 360; j+=segment)

float x = 325 + (radius*cos(radians(j)));

这就是导致舍入错误的原因。

而且,如果您使i获得的价值大于60该程序将永远不会结束。

于 2013-09-23T00:02:50.160 回答
1

使用double而不是浮点数来最小化表示错误。

更改 for 循环以减少错误。

for (int k = 0; k < div; k++) {
    int j = k * 360 / div; 

这将为您提供j可能更正确的不同值。

于 2013-09-23T00:17:03.177 回答