4 ms·
> cosine repeats every 2pi > We can do better since the cosine values are equivalent every multiple of pi, except that the sign flips. There is one more step
by sampo 3y ago
> cosine repeats every 2pi
> We can do better since the cosine values are equivalent every multiple of pi, except that the sign flips.
There is one more step to take: Each π/2 long segment has identical shape, they are just pointing up or down (like you already noticed), and left or right. So you can reduce you basic domain down to not just 0...π, but to 0...π/2.
- amelius 3y agoBut that takes extra clock cycles, since now you have to fiddle with the sign.
- Someone 3y agoI think it’s likely that you get that more than back by having to do (at least) one iteration fewer. Those who know more about this: educate me.
- adgjlsfhk1 3y agoPretty much every implementation does reduction mod pi/2. Switching polynomials is basically free (and halving the domain significantly reduces the number of terms needed).
- IIAOPSW 3y agoAnd you can keep going with this logic, building cos from 0-x by recursively calculating cos from 0-x/2 then mirroring over some line if needed. Eventually you hit machine precision limit aka the base case cos(0) = 1.
- ajross 3y agoAnd still further: the function can be piecewise decomposed into separate polynomials, which is what the pervasive SunPro code in everyone's libc does. There's one "mostly parabolic" function to handle the curvy top, and another "mostly linear" one to handle the zero crossing region.
- gmiller123456 3y agoYou can actually reduce it to n/4 as the range from 0 to pi/2 is the same shape as the remaining 3 segments, just mirrored along different axis.