为什么正弦曲线会随时间变化?

时间:2017-05-25 10:20:46

标签: processing

下面的代码根据正弦曲线绘制椭圆。

i的增量适合绘图的大小,角度增量应该是周期性的,因为它是2 * pi的因子,但曲线似乎加速并随时间变化。为什么曲线不恒定?

float r = 3;
float the = 0;

void setup()
{    
  size( 1500, 300 );
  frameRate( 500 );
  smooth();
} 

void draw()
{
  translate( 0, height/2 );
  background(0);
  for ( int i=0; i<1500; i+=1 )
  {
     ellipse( i * 10, sin( the ) * 50, r, r );   
     the += ( 2 * PI ) / 150;
  }
}

2 个答案:

答案 0 :(得分:3)

这肯定与浮点的精度有关,如果你每次只用the修改TWO_PI,曲线几乎不变,几乎没有移动。但你仍然可以注意到一些点经常移动1个像素。

float r = 3;
float the = 0;

void setup()
{    
  size( 1500, 300 );
  frameRate( 500 );
  smooth();
} 

void draw()
{
  translate( 0, height/2 );
  background(0);
  for ( int i=0; i<1500; i+=1 )
  {
     ellipse( i * 10, sin( the ) * 50, r, r );   
     the += ( 2 * PI ) / 150;
     the %= TWO_PI;
  }
}

彼得的答案也有效,它实现了几乎相同的东西,但通过更多具体和精确将其设置为零,而不是从TWO_PI得到余数

更新

正如彼得在下面的评论中指出的那样,为了使你的草图更有效率并且更加减少点的移动,你可以减少for循环以仅迭代150并移动{{1}离开for循环:

the %= TWO_PI

答案 1 :(得分:2)

变量the是一个浮点数,它会在无穷无尽的绘制循环中不断增加。在某些时候the流过并从0开始(或者是负数)。从这一点开始,x和y坐标不会相关。然后图表开始闪烁。

如果你在绘制循环结束时初始化the变量会有所帮助。

float r = 3;
float the = 0;

void setup()
{    
  size( 1500, 300 );
  frameRate( 500 );
  smooth();
} 

void draw()
{
  translate( 0, height/2 );
  background(0);
  for ( int i=0; i<1500; i+=1 )
  {
     ellipse( i * 10, sin( the ) * 50, r, r );   
     the += ( 2 * PI ) / 150;
  }

  the = 0;
}