Reputation: 1166
I have a code that deals with azimutal operations.
I'd like to distinguish if the azimuth is near 0,100,200,300,400 or 0, PI/2, PI, PI*(3/2), 2*PI, (N, E, S, W)
.
The most of cases I'm going to receive an angle that is not in this range so I'd need the fastest way to discard I have these values.
I want to do this to have control on line equations for pure horizontal or vertical azimuths.
Of course I'm going to use epsilon approach.
So I'd have:
if Math.abs(azi)< 0.0000001 ...
else if Math.abs(azi-100)< 0.0000001 ...
else Math.abs(azi-200)< 0.0000001 ...
else Math.abs(azi-300)< 0.0000001 ...
else Math.abs(azi-400)< 0.0000001 ...
else other
As you can see I have to check 5 conditions to check I have 'other' value.
By other hand, you know that sin(N) =0, sin(S) = 0 and cos(E)=0 and cos(W) =0, so:
if Math.abs(Math.cos(azi) ) < 0.0000001 ...
else if Math.abs(Math.sin(azi) ) < 0.0000001 ...
else other
Now I have two conditions with a math trigonometric operation vs 5 simple aritmetic operations. As you can see at jsperf, arithmetic is faster.
My question is: is there any other fast way to do this?
Upvotes: 0
Views: 76
Reputation: 67
I'm not sure how modulus performance compares to other arithmetic but that way you can at least fit it in one line.
if ((azi + 0.0000001) % 100) < 0.0000002 ...
else other
This should do the same thing as your code besides potential rounding errors.
I tried it on your page and it seems to perform about three times faster.
Upvotes: 1