# Generating a sawtooth function with a variable frequency

So I'm trying to write a script that produces a sawtooth function using the equation:

s = 2 a / π atan ( cot ( π f t ) )

Where:

a : amplitude

f : frequency

t : time

It's all working fine when f is constant. But when f is variable (especially with a steep slope) it fails. In fact when f is falling, I get an inverse sawtooth signal (since df / dt is negative, f * t is going backward). Even when it's positive, though the sawtooth function looks correct, its fundamental frequency is not consistent with the value of f.

I tried to convolve f with a [-1,1] kernel and get its local derivative... But I'm not sure I really know what I'm doing at this point...

What I need to do is find a transformation for f (that probably involves its local derivative) that guarantees the sawtooth function does not invert, and that the frequency of the pulses is always consistent with f. Can anyone help?

Some context: what I'm ultimately trying to do is use the sawtooth function as the index for a wavetable scanner. I know there are easier ways to do wavetable synthesis but I need my process to be end-to-end differentiable.

• there's really no reason to use a concatenation of arcus tangens and cotangens just to get a (nearly everywhere) differentiable sawtooth; the naive $s = a\left(tf \mod \frac 1f\right)$ is differentiable in all the same points – and in the points where it isn't, your solution's gradient isn't bounded, either. – Marcus Müller Oct 20 '20 at 9:40