Live data from Hacker News

Implementing Cosine in C from Scratch (2020)

austinhenley.com

21–30 of 139 posts

Re: Implementing Cosine in C from Scratch (2020)

#21
You are doing the polynomial evaluation wrong for Taylor Series. First of all you should be using Horner's Method to reduce the number of multiplications needed and then you should be using FMA to increase precision of the solution. https://momentsingraphics.de/FMA.html

Re: Implementing Cosine in C from Scratch (2020)

#22
post #4

lookup tables and lerp are the most common solution I've seen (for a wide range of functions). You can also memorize with an LRU cache.

> You can also memorize with an LRU cache. That's probably not going to perform well for an operation this fast. The computation is faster than main memory read.

You can fit quite a large LRU cache in the L2 cache of the processor. You never want to go to main memory for a lerp table.

Re: Implementing Cosine in C from Scratch (2020)

#23

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.

IIRC this comes up in the derivation of the boltzmann distribution. I also recall stirlings approximation for x!.

Re: Implementing Cosine in C from Scratch (2020)

#25
post #4

lookup tables and lerp are the most common solution I've seen (for a wide range of functions). You can also memorize with an LRU cache.

Yeah, lerping into a lookup table is common in audio and (old school) games.

A common trick to make that faster is to not use doubles and radians to represent the phase. Instead, represent phase using an integer in some power-of-two range. That lets you truncate the phase to fit in a single period using a bit mask instead of the relatively slow modulo.

Re: Implementing Cosine in C from Scratch (2020)

#28
Audio stuff uses different methods depending on the application. Additive oscillators need to be accurate and can use some closed forms and series, mostly people use Taylor and quadratic interpolation as the article shows. For tables remember you only really need to compute amd store one quadrant and shift it around. But for LFOs people use all manner of dirty and quick methods like Bhaskara.

https://en.wikipedia.org/wiki/Bhaskara_I%27s_sine_approximat...

Re: Implementing Cosine in C from Scratch (2020)

#29
post #19

Here's a solution which is vectorizable: http://gallium.inria.fr/blog/fast-vectorizable-math-approx/ I've also read that Chebyshev polynomials are far better for approximating functions than Taylor series (eg https://en.wikipedia.org/wiki/Approximation_theory )

This matters less once you put things through the horner scheme. And if you are not you are leaving performance on the table.
Post reply on HN