Reputation: 67928
I'm thinking of a wheel of fortune type of thing where you have to check if a marker lands on a slot. Visually, we can see 0, 2pi, 4pi, etc... are in the same position. How do I check if 0 is equal to 2pi/4pi programmatically? Assuming I have the radius as well, I thought, maybe I have to convert it to cartesian coordinates first and then compare it. However, is there a better way to do this?
Edit: Also, I should make clear that the mark can land anywhere in between a slot. For example, the marker could be anywhere in between 0 to pi/6.
Upvotes: 0
Views: 309
Reputation: 8192
Is this what you want?
var smallestEquivalentValueInRadians = originalValueInRadians % (2 * Math.PI);
If you want to compare, you can do:
a % (2 * Math.PI) === b % (2 * Math.PI)
%
is the modulo operator, basically it subtracts the second operand from the first, as many times as it can (assuming you are dealing with positive numbers).
To cater for negative values:
function normalizeRadian(a) {
var circle = Math.PI * 2;
a = a % circle;
if (a < 0) {
a += circle;
}
return a;
}
Also when comparing floats, it's a good idea to have some "fuzzyness", since opperations on them can be imprecise.
function fuzzyEqual(a, b) {
var fuzz = 0.001;
return a < b + fuzz && a > b - fuzz;
}
So the complete solution is:
function fuzzyEqualRadians(a, b) {
return fuzzyEqual(normalizeRadian(a), normalizeRadian(b));
}
Upvotes: 1