Ways to generate triangle wave function.

5.8k Views Asked by At

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.

enter image description here 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.

2

There are 2 best solutions below

1
On BEST ANSWER

You can take a Fourier series of your function as it's periodic with period 2. This gives a series of $$\dfrac{1}{2} - \dfrac{4}{\pi^2} \sum_{n=1}^{\infty} \dfrac{\cos((2n-1)\pi t)}{(2n-1)^2}.$$

For instance, the first 5 terms of the series give an approximation

enter image description here

and the more terms you take, the better the approximation. E.g. 50 terms looks almost exactly the same:

enter image description here

0
On

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)$$