0

So i've written some code which generates a sine wave at a frequency which you can control.

The goal is this: Every time the sine wave has a value of 0 (i.e. twice a cycle), a 16 step loop adds one to itself.

For example: A sine wave at 5Hz cycles every 0.2 seconds(T = 1/f). The theory is that since you can control the rate at which the wave travels, the higher the frequency the quicker the loop will iterate. Therefore you would be able to control the rate at which the 16step loop increments itself by a time (in seconds) by simply adjusting the frequency of the sine wave.

    double frequency = 5.0;
    const float fTwoPI = 2 * M_PI;  //assigning (2* Pi) as a variable
    double fPhaseInc = (frequency) / getSampleRate();
    double sinWave = 0;


   fPhasePos += fPhaseInc;
        if (fPhasePos > fTwoPI)
            fPhasePos -= fTwoPI;
        
        sinWave = ( sin(fPhasePos));
        cout << sinWave << endl;

Then we apply this wave to another loop


 int pattern = 0;

 if (sinWave == 0 ) {
            if(pattern == 16) {
                pattern=0;
            }
            pattern++;

This code doesn't quite work however and i'm not sure why. When i print the values for sineWave, the wave doesn't start at 0, and never hits 0, and when the wave reaches 1, it repeats multiple times at 1.

Why is this happening when a sine wave should start at 0, and only reach 1 once per cycle.

Would this theory work in the sense that loop iterations could be controlled by a time? Is there a more efficient way to control loop iterations with a time value you can choose ?

Quite new to all this, any suggestions/corrections would be appreciated

  • It's for the same reason why `.1+.2` is not `.3`. If you print out the value of `fPhasePos` every time the shown code adds to it, and use the maximum possible precision, you will not get the results you're expecting to get. – Sam Varshavchik Jan 23 '23 at 01:55
  • Linked to the floating point concern is the fact that the sine has period 2pi, but pi itself is an irrational number that (among other things) so it and multiples of it cannot be represented exactly in any finite floating point type. Because of that `sin()` only returns zero in specific circumstances based on interaction of errors in the argument and imprecision in the [finite] algorithm to compute the result. There are various alternatives to checking for `sin()` returning `0` [as in your code] (e.g. looking for cases where `sin(x)` and `sin(x + suitable_delta)` have different sign). – Peter Jan 23 '23 at 03:08

0 Answers0