I am writing a JavaScript application to generate random points on the surface of a sphere. I found this formula on Wolfram to get phi and theta (http://mathworld.wolfram.com/SpherePointPicking.html#eqn2). Phi is the one I am having issues with phi = cos^(-1)(2v-1)
where v is a random variables of (0,1). The following is the JavaScript I wrote to calculate phi. However, when it executes it returns NaN very often. Can anyone tell me if I am misinterpreting the formula? The only thing I can think of is Math.random() generates (0,1] and the 0 can throw an error. But in running multiple tests, I don't think Math.random()
is generating a 0 every time I execute the line.
var phi = Math.acos(2 * (Math.random()) * - 1);
It's because the arc cosine of a number greater than 1 (the Math.acos()
function) returns NaN
, and Math.random() * 2
sometimes returns numbers greater than 1.
How to fix?
I see the maths cos^(-1)(2v-1)
as something like
v = someValue;
Math.acos(2 * v) - 1;
To do this with you want, you probably want
phi = Math.acos(2 * Math.random() - 1);
as your Javascript code.
Conclusion:
To fix, all you need to do is replace
phi = Math.acos(2 * Math.random() * - 1);
with
phi = Math.acos(2 * Math.random() - 1);
(remove the * -1)