Live data from Hacker News

Implementing Cosine in C from Scratch (2020)

austinhenley.com

31–40 of 139 posts

Re: Implementing Cosine in C from Scratch (2020)

#32
If you want sinusoidal oscillation over time, then you can integrate the second-order differential equation x'' = -ω² x instead. This only costs a few arithmetic instructions per time step. On the other hand, it adds dependency on a state other than the current time, and you must be careful to use energy-conserving integration.

Re: Implementing Cosine in C from Scratch (2020)

#33
post #15
post #12

The implementation of the __cos kernel in Musl is actually quite elegant. After reducing the input to the range [-pi/4, pi/4], it just applies the best degree-14 polynomial for approximating the cosine on this interval. It turns out that this suffices for having an error that is less than the machine precision. The coefficients of this polynomial can be computed with the Remez algorithm, but even truncating the Cheby…

https://github.com/ifduyue/musl/blob/master/src/math/__cos.c

> Input y is the tail of x.

What does "tail" mean in this context?

Re: Implementing Cosine in C from Scratch (2020)

#35
I did the same thing for sqrt() seven years ago. It benchmarked at about five times faster than math.h/libm, but the trade was a reduction in the maximum value of the result. My version would not produce accurate results for inputs greater than 2^16. It did work very well for generating real-time laser pointing X/Y coordinates for an Archimedean Spiral.

https://en.wikipedia.org/wiki/Archimedean_spiral

(This was on a MSP430 platform with a FPU that only did multiplication.)

Re: Implementing Cosine in C from Scratch (2020)

#36

Mandatory Physics "troll" comment: For small angles, sin(x) ~= x and cos(x) ~= 1 -- the ["small angle approximation"]( https://en.wikipedia.org/wiki/Small-angle_approximation ) It's actually kind of ridiculous how many times it comes up and works well enough in undergraduate Mechanics.

Useful in astronomy and telephoto photography as well.

Re: Implementing Cosine in C from Scratch (2020)

#39
post #24

>I couldn't find any notable projects on GitHub that use a table for trig functions, but I'm sure they exist. Doom?

Julia?

Julia uses a very similar approach to musl here. Reduction mod 2pi followed by polynomial kernel. We use tables for `exp` and `log`, but the trig functions have good reductions so we use those instead. The implementation is here https://github.com/JuliaLang/julia/blob/03af78108afe6058f54c... for anyone interested.
Post reply on HN