2011-12-29 141 views
1

由於某些原因,當我嘗試通過檢查點的半徑來製作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 < 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... 
        } 
       } 
     } 
} 
+0

我不我不明白這個問題。什麼是「一個點的半徑」?另外,嘗試提供一個實際編譯和運行的最小示例。沒有這些,很難理解你的代碼應該做什麼。 – sleske 2011-12-29 18:37:14

+0

移動int radius =直徑/ 2;出於效率的原因,在你的循環之外。 And do double Cr = Math.hypot(Math.hypot(cX,cY),cZ); 這個更簡單,更不容易出錯,並且(除非我的數學學位是完全浪費時間)應該可以工作。 編輯:@BRPocock的想法更好 – 2012-01-03 00:12:54

回答

2

假設你的球體的原點是(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); 
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); 
    } 
}