爪哇8(@Arnauld的改性第三算法),131个 126 119 111 109字节
v->{double k=2*M.random()-1,t=M.sqrt(1-k*k),r[]={k,M.cos(k=2*M.PI*M.random())*t,M.sin(k)*t};return r;}
@Arnauld的JavaScript答案端口,请确保对其进行投票!
-2个字节,感谢@OlivierGrégoire。
这实现为:
k=N∩[−1,1)
t=1−k2−−−−−√
u=2π×(N∩[0,1))
x,y,z={k,cos(u)×t,sin(u)×t}
在线尝试。
先前的第3种算法实现(131 126 119字节):
Math M;v->{double k=2*M.random()-1,t=2*M.PI*M.random();return k+","+M.cos(t)*M.sin(k=M.acos(k))+","+M.sin(t)*M.sin(k);}
实施为:
k=N∩[−1,1)
t=2π×(N∩[0,1))
x,y,z={k,cos(t)×sin(arccos(k)),sin(t)×sin(arccos(k))}
在线尝试。
说明:
Math M; // Math on class-level to use for static calls to save bytes
v->{ // Method with empty unused parameter & double-array return
double k=2*M.random()-1, // Get a random value in the range [-1,1)
t=M.sqrt(1-k*k), // Calculate the square-root of 1-k^2
r[]={ // Create the result-array, containing:
k, // X: the random value `k`
M.cos(k=2*M.PI // Y: first change `k` to TAU (2*PI)
*M.random()// multiplied by a random [0,1) value
) // Take the cosine of that
*t, // and multiply it by `t`
M.sin(k) // Z: Also take the sine of the new `k` (TAU * random)
*t}; // And multiply it by `t` as well
return r;} // Return this array as result
爪哇8(第二算法),153个 143字节
v->{double x=2,y=2,z=2,l;for(;(l=Math.sqrt(x*x+y*y+z*z))>1;y=m(),z=m())x=m();return x/l+","+y/l+","+z/l;};double m(){return Math.random()*2-1;}
在线尝试。
第二种算法:
v->{ // Method with empty unused parameter & String return-type
double x=2,y=2,z=2,l; // Start results a,b,c all at 2
for(;(l=Math.sqrt(x*x+y*y+z*z)) // Loop as long as the hypotenuse of x,y,z
>1; // is larger than 1
y=m(),z=m())x=m(); // Calculate a new x, y, and z
return x/l+","+y/l+","+z/l;} // And return the normalized x,y,z as result
double m(){ // Separated method to reduce bytes, which will:
return Math.random()*2-1;} // Return a random value in the range [-1,1)