用Java绘制球体

出于某种原因,当我尝试通过检查点的半径来制作Java中的球体时,它给了我一个立方体而不是一个球体。 我的代码或公式有问题吗?

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  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... } } } } 

假设你的球体的原点是(0,0,0),我认为你有一个额外的平方根。

另外,乘以X * X比Math.pow(X,2)快几倍……

我也会将半径计算移到循环之外,并使其像其余部分一样double ,以防万一会出现舍入错误。

(您可以使用X += foo替换X++增量,以使此版本可以使用更小或更大的步骤。)

  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); 

更优化的解决方案是:

  int r2=radius*radius; for(int X = -radius; X <= radius; X++ ){ int x2=X*X; for(int Y = -radius; Y <= radius; Y++ ){ int y2=Y*Y; for(int Z = -radius; Z <= radius; Z++ ) if(x2 + y2 + (Z * Z) <= r2) SetInShere(X,Y,Z); } }