-1

I need to increase/reduce phi angle by value d infinitely. (d can be negative or positive).

"Infinitely" means that cycling change can happen as much as long. But to avoid overflowing it is necessary "drop" value, relying on periodicity of sin () and cos (). (0 <=> 2*pi <=> 2*n*pi).

How it can be implemented in function? (e.g. double stepAngle(double phi, double d)).

Eric J.
  • 147,927
  • 63
  • 340
  • 553
shau-kote
  • 1,110
  • 3
  • 12
  • 24

3 Answers3

2

The standard library functions just "do the right thing" for values > 2*pi, you don't have to do anything:

int main() {
  double pi = 3.14159265359;
  double x = 2.5;
  cout << sin(x) << endl;
  cout << sin(x + 2*pi) << endl;
  cout << sin(x - 8*pi) << endl;
}

These will all print the same value; try it out.

Thomas Nelson
  • 693
  • 5
  • 17
  • I know it. But if a value of an angle increases "infinitely", there is an overflowing sooner or later. Therefore I ask this question. – shau-kote Feb 12 '13 at 12:47
  • Also as one gets further and further away from 0, there is a loss of precision because the number of bits used for the mantissa is finite. If you have a number like 3000000000000 and add 0.001 (using an IEEE double), the result is still 3000000000000. If you add 0.01 instead, that change can be represented within the available precision. – Eric J. Feb 12 '13 at 17:35
2

This is possible with fmod fairly easily.

 double stepAngle(double phi, double d)
 {
    double newPhi = phi += fmod(2*pi, d);
    if(newPhi > 2*pi)
    {
      newPhi -= 2*pi;
    }
    if(newPhi < 0)
    {
      newPhi += 2*pi;
    }

    return newPhi;
lcs
  • 4,227
  • 17
  • 36
1

One approach is to renormalize to the desired range:

while (d > 2*pi) d -= 2*pi;
while (d < 0) d += 2*pi;

That will be efficient as long as d is not extremely far outside the range of 0..2*pi.

Eric J.
  • 147,927
  • 63
  • 340
  • 553