Can You Find Something Mod 2Pi in JavaScript?
EDIT: I have an angle from using Math.atan2() which I then want开发者_如何转开发 to add or subtract values from. However, this addition and subtraction sometimes means the angle is greater that pi or less than -pi and I'm looking for a way to get one of these outside angles back into the correct range.
I'm trying to find a value mod 2pi in JavaScipt using the following code:
foo % Math.PI * 2;
However, it always just returns foo, even if I try this:
var bar = Math.PI * 2;
foo % bar;
Can anyone explain to me why this doesn't work?
DLiKS
You aren't making an assignment:
foo = foo % Math.PI * 2;
Or:
foo %= Math.PI * 2;
EDIT:
To paraphrase your updated question, you have a value foo, which may be any angle, however you want foo to be in the range [-pi,pi]. You need to do this programatically:
foo %= 2 * Math.PI; // Now in the range [-2pi,2pi]
if (Math.abs(foo) > Math.PI) {
foo -= 2 * Math.PI * Math.sign(foo);
}
Types. Math.Pi is a double. Any (Int % Double) will return the Int side.
Try:
<script type="text/javascript">
var bar = parseInt(Math.PI * 2 * 10000);
document.write(bar / 10000 + "<br/>");
var foo = 60000;
foo %= bar;
document.write(foo / 10000 + "<br />");
</script>
精彩评论