Fixing the sawtooth wave

In my most recent post, I made some new oscillators, but noted the sound seems off for them. The most obvious of these examples is with the sawtooth wave. I had plotted out graphs of each oscillator function, and while the math and graphs looked right, the sound was definitely wrong. This time, I found another example of a Java oscillator implementation, made a chart of the actual sample values it produced, and compared it with the actual sample values my oscillators produced. The example had only square, sawtooth and sine, so I'll need to find a different triangle wave example.

There wasn't much difference between the sine and square waves, but my sawtooth wave clearly has issues.

Regular sawtooth wave on the left, my implementation on the right

Yikes! That's definitely not right. So, why is it going awry? To find out, I'll need to double-check the math. In my scenario, the first value that is clearly wrong is when x = 52 (which is halfway through the expected period with a frequency of 428, sample rate of 44khz, and amplitude of 32767). My function produces a value of 306, but the example produces a value of -32449.

The Example Function

In the example function, it starts by dividing x by the number of samples in a period (103). For x = 52, this value is 0.505 (rounded). Let's call this value z. It then performs the following calculation:

y = 2 * (z - Math.floor(z + 0.5))

This produces a y value of -0.99 (rounded) which, when multiplied by the amplitude, gets us our final value of -32449.

My Function

In my function, my mistake was where I put the 2. It looks more like this:

y = (2 * z - Math.floor(z + 0.5))

Which means the 2 is multiplied by the z value instead of z - Math.floor(z + 0.5). This produces an incorrect value. Once I fixed this, the sawtooth wave sounded much better, and the graph resembled the one on the left.

I still need to fix the square and triangle waves, but this one was the most obviously wrong. 

Comments