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)