Reputation: 221
Can someone help me troubleshoot this? In the below code, circx
and circy
are being initialized appropriately, but theta
is always initializing to 1! The console logs theta = 1
every time I load the page.
var circx = Math.floor(Math.random() * Number.MAX_VALUE) % papwidth;
var circy = Math.floor(Math.random() * Number.MAX_VALUE) % papheight;
/*
circx, circy: initial positions of circle on the papern
*/
var mycirc = paper.circle(circx, circy, 10);
mycirc.attr("fill","#F9C624");
var theta = Math.floor(Math.random() * Number.MAX_VALUE) % 4 + 1;
/*
theta = 1 <---> object moving at a 45-degree angle
theta = 2 <---> object moving at a 135-degree angle
theta = 3 <---> object moving at a 225-degree angle
theta = 4 <---> object moving at a 315 degree angle
*/
console.log("theta = " + theta);
This makes no sense!
Upvotes: 0
Views: 76
Reputation: 4603
var theta = Math.round(Math.random() * 3) + 1;
Should just works fine.
Addendum:
As Tom Fenech pointed out, Math.random()
produces a number from 0 (incl.) to 1 (excl.), which allows for a more intuitive solution:
var theta = Math.ceil(Math.random() * 4);
Upvotes: 4
Reputation: 60748
> Math.random() * Number.MAX_VALUE
8.365923028455995e+307
You see that e+307
? That means it ends in 307 zeroes. Doubles are not stored in integer precision. Take that mod 4 and add 1, and you always get 1. (Or you do 99.99999...% of the time).
Upvotes: 7