3

Background : The other day I felt like updating my knowledge with GUI programming so I made a small application that rendered a multivalued periodic function $\mathbb R^3 \to \mathbb [0 ,255]^3$. The three in-dimensions being $(x,y,t)$ and the three out-dimensions $(R,G,B)$.

enter image description here

The problem I encountered was that my math librarys "sin" routine which I had intended to use was too slow. I instead tried a sawtooth-like approximation using round, and fabs which was much faster but not nearly as pretty.

How can I make a computationally cheap but still relatively smooth sine-like curve for purposes like this?

My own ideas of how to do it have mostly been in the realms of low-order polynomial approximations and interpolation.


Edit After implementation in C and some fiddling I managed to get Claude's proposals

  • Mahabhaskariya : 3% CPU load and
  • RobJohn : 2% CPU load. This is same as my edgy saw-tooth above.

This can be compared to cmath.h functions

  • double precision "sin" which took 10% CPU.
  • single precision "sinf" which took 5% and

Now included in CPU load is also everything else that is required by QT to plot to screen and so on so it is quite possible that the actual sin routines are many orders of magnitude faster. Replacing sin by a function that returns 0 gives 1% CPU load. So it is possible that my implementation of Claudes fonctions are 2-3 and 5-10 times faster. If we need accuracy in these estimates we should do more careful time measurements, but as this mostly is an artistic application it is good enough for now.

mathreadler
  • 25,824
  • 2
    If high accuracy is not needed and the $x$ terms are not particularly large, use the first few terms of the $\sin(x)$ taylor series – Henry Lee May 06 '21 at 14:12
  • 1
    Polynomial approximations are probably your best bet. Have you tried taking the third or fifth order taylor polynomial for sin (restricting to a nice interval like $[-\pi/2,\pi/2]$ and using the symmetries of $\sin$ to get values from this interval)? – Dan Rust May 06 '21 at 14:13
  • How much precise do you want it to be ? Is something almost behaving like a sine (like $1-\left(2/\pi x-1\right)^2$ for $x \in [0,\pi]$) enough for you ? – nicomezi May 06 '21 at 14:16
  • 1
    If you want more accurate, just tell. – Claude Leibovici May 06 '21 at 14:53

1 Answers1

3

This one which is $\color{red}{\large 1,400}$ years old $$\sin(x) \simeq \frac{16 (\pi -x) x}{5 \pi ^2-4 (\pi -x) x}\qquad (0\leq x\leq\pi)$$

was proposed by Mahabhaskariya of Bhaskara I, a seventh-century Indian mathematician.

Now, if you look here, you will find nice ones; in particular the one given by @robjohn $$\sin(x)\sim\frac{31}{10\pi^2}(\pi-x)x+\frac{18}{5\pi^4}(\pi-x)^2x^2$$