For some reason, when I try to make a sphere in Java by checking the radius of points, it gives me a cube instead of a sphere. Is the problem with my code or my formula?
for(double X = 0; X < diameter; X++ )
{
//mcspace.logger.info("X = " + Double.toString(X));
for(double Y = 0; Y < diameter; Y++ )
{
//mcspace.logger.info("Y = " + Double.toString(Y));
for(double Z = 0; Z < diameter; Z++ )
{
//mcspace.logger.info("Z = " + Double.toString(Z));
int radius = diameter / 2;
double cX = X;
double cZ = Z;
double cY = Y;
if (X > radius){cX -= radius;}
if (Y > radius){cY -= radius;}
if (Z > radius){cZ -= radius;}
double Cr = Math.sqrt(Math.sqrt(Math.pow(cX,2) + Math.pow(cY,2)) + Math.pow(cZ,2));
if(Cr <= radius)
{
SetInShere(X,Y,Z);
// This is just a function that is in my code but the problem is that almost all the points are in the sphere, I almost always get a cube instead of a sphere...
}
}
}
}
解决方案
Assuming that your sphere's origin is (0,0,0), I think you have an extra square root in there.
Also, multiplying X*X is several times faster than Math.pow(X,2)…
I would also move the radius computation outside of the loop, and make it a double like the rest, just in case the rounding errors would come to bite you.
(You could replace the X++ increments with X += foo to make this version work with smaller or larger steps, as well.)
double radius = diameter / 2;
for(double X = -radius; X < radius; X++ )
for(double Y = -radius; Y < radius; Y++ )
for(double Z = -radius; Z < radius; Z++ )
if(Math.sqrt((X * X) + (Y * Y) + (Z * Z)) <= radius)
SetInShere(X,Y,Z);