用Java绘制球体

时间:2011-12-29 17:52:50

标签: java math geometry

出于某种原因,当我尝试通过检查点的半径来制作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 < 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...
                    }
                }
         }
}

2 个答案:

答案 0 :(得分:2)

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

此外,乘以X * X的速度比Math.pow(X,2) ...

快几倍

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

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

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

答案 1 :(得分:0)

更优化的解决方案是:

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