Java 在海龟程序中绘制圆

Java 在海龟程序中绘制圆,java,processing,Java,Processing,我目前正在编写一个由Turtle逻辑驱动的处理(如语言中所示)草图(请参阅)。这意味着我从当前坐标到提供的坐标绘制了一条线。然后,提供的坐标将成为新的当前坐标。我想近似一个圆,并用三角法写了一段简单的代码。代码如下所示: void drawCircle(int radius){ // The circle center is radius amount to the left of the current xpos int steps = 16; double step = T

我目前正在编写一个由Turtle逻辑驱动的处理(如语言中所示)草图(请参阅)。这意味着我从当前坐标到提供的坐标绘制了一条线。然后,提供的坐标将成为新的当前坐标。我想近似一个圆,并用三角法写了一段简单的代码。代码如下所示:

void drawCircle(int radius){
   // The circle center is radius amount to the left of the current xpos
   int steps = 16;
   double step = TWO_PI /steps;

   for(double theta = step; theta <= TWO_PI; theta += step){
      float deltaX = cos((float)theta) - cos((float)(theta - step));
      float deltaY = sin((float)theta) - sin((float)(theta - step));

      moveXY(deltaX*radius, deltaY*radius);
   }

}
void绘图圆(整数半径){
//圆心是当前XPO左侧的半径
int步数=16;
双步=两步;

对于(double theta=step;thetaFloat和sine/cosine应该足够精确。问题是:你在平面上的位置有多精确?如果这个位置是以像素为单位测量的,那么你的每个浮点值在每一步后都被舍入为整数。然后,精度的损失加起来。

在循环的每次迭代中,你都是c在不考虑当前坐标的情况下计算三角洲。因此,实际上,你是“航位推算”,这总是不准确的,因为每一步都会产生误差

既然你知道你想要一个圆,另一种方法是在每次迭代中,首先确定你想要到达的圆上的实际点,然后计算到达该点的增量-因此类似于下面的内容(但我必须承认我没有测试过它!):

void绘图圆(整数半径){
//圆心是当前XPO左侧的半径
int步数=16;
双步=两步;
float previousX=0;
先前浮动=半径;

对于(double theta=step;theta位置变量被存储为int,这导致了偏差。在将其切换为float后,错误被纠正。我的所有圆现在都很完美!但是由于位置是由相同的算法生成的,所以位置应该几乎相同。问题出在位置a的方式上您已保存。修复此问题会生成完美的圆圈!不过感谢您的贡献。
void drawCircle(int radius){
   // The circle center is radius amount to the left of the current xpos
   int steps = 16;
   double step = TWO_PI /steps;

   float previousX = 0;
   float previousY = radius;

   for(double theta = step; theta <= TWO_PI; theta += step){
       float thisX = radius * sin((float)theta);
       float thisY = radius * cos((float)theta);

       moveXY(thisX - previousX, thisY - previousY);

      previousX = thisX;
      previousY = thisY;
    }

}