Is there any advantage to restraining the angle passed to trigonometric functions?
I was wondering whether there was any advantage to clamping the angle passed to trigonometric functions between 0
and Math.PI * 2
? I had a function which made heavy use of trigonometric functions, and someone in the project added this to the beggining:
angle %= Math.PI * 2;
Is there any advantage to this? Are the trigonometric functions faster if the angle passed is between those values? If so, sho开发者_开发知识库uldn't they clamp it themselves? Is there any other case where equivalent angles should be clamped?
The language is JavaScript, most likely to be run on V8 and SpiderMonkey.
Since most (on-die) algorithms for computing trigonometric functions use some variant of CORDIC, my bet is that those values are getting clamped within [0, Pi/2) anyway at the entry point of the trig function call.
That being said, if you have a way to keep the angles close to zero throughout the algorithm, it is probably wise to do it. Indeed, the value of sin(10^42) is pretty much undefined, since the granularity in the 10^42 range is around 10^25.
This means for instance that if you are to add angles, and if by doing so, they can get large in magnitude, then you should consider periodically clamping them. But it is unneccessary to clamp them just before the trigonometric function call.
An advantage of clamping angles to the range -pi/4 to pi/4 (use sine or cosine as appropriate) is that you can ensure that if the angles are computed using some approximation of pi, range reduction is performed using that same approximation. Such an approach will have two benefits: it will improve the accuracy of things like the sine of 180 degrees or the cosine of 90 degrees, and it will avoid having math libraries waste computational cycles in an effort to perform super-accurate range reduction by a "more precise" approximation of pi which doesn't match the one used in computing the angles.
Consider, for example, the sine of 2⁴⁸ * pi. The best double
approximation of pi, times 2^48, is 884279719003555, which happens to also be the best double approximation of 2⁴⁸π. The actual value of 2⁴⁸π is 884279719003555.03447074. Mod-reducing the best double approximation the former value by the best double approximation of pi would yield zero, the sine of which equals the correct sine of 2⁴⁸π. Mod-reducing by π the value scaled up by the best approximation of pi will yield -0.03447074, the sine of which is -0.03446278.
精彩评论