I recently when searching for parameters on a unit cube in $\mathbb{R}^9$ (we all have our more or less peculiar hobbies, don't we?) found a practical reason to implement a triangle wave function $t(x)$ which can be defined as:
$$t(x) = \left\{ \begin{array}{ll}-x, & \forall x \in [-1,0]\\\phantom{-}x, & \forall x \in [\,\,\,\,\,0,1] \\ t(x+2),& \forall x \in \mathbb{R}\end{array}\right.$$
What techniques do there exist which would give nice properties for approximations of this function? "Nice properties" include (but are not limited to) :
- good fit in some sense (for example $L^2$)
- smooth continous derivatives
- practical/easy to compute
- easy to implement
- fast to compute
Own work Having learned the use for fourier transform in my field my first reaction was to do a fast fourier transform (fft) to generate the function with the use of the fourier transform's basis functions (sines and cosines). The coefficients for these diminish quite fast ($\mathcal{O}(n^2)$) with number of coefficients for this particular function which is nice as we get then a compressed representation and also we get continuity of derivatives at the integer points which is a nice property in many cases.
Function to be approximated in blue and a smooth approximation of up to order 3 sines and cosines. Honestly it has been tweaked a bit to match the maxima and minima better – how to accomplish that automatically could maybe be a follow up question.
Best Answer
Here is a way to generate the triangle wave. $$y = \arcsin (\cos x)$$
Here is a way to generate the sawtooth wave. $$y = -\text{arccot} (\tan x)$$
Here is a way to generate the square wave. $$y = \arctan (\sin x) + \text{arccot} (\sin x)$$