2013-05-08 37 views
1

我正在嘗試使用Math.pow找到整數的小數組的幾何平均數。 這是我第一次使用這種語法,我不知道如何去完成我的代碼。如何使用Math.pow找到整數的幾何平均數使用Math.pow

我目前正在經歷去年的考試試卷,這是其中一個問題。

請原諒我的代碼中的任何錯誤。我仍然在學習Java。

public class AverageOfArray { 

public static void main(String []args){ 

    int [] data = new int[3]; 
    data[0] = 2; 
    data[1] = 4; 
    data[2] = 8; 

    int y = 0; 
    int sum = 0; 
    for(int i = 0; i < data.length; i++){ 
     sum = sum + data[i]; 
     y++; 
    } 

    Math.pow(sum, 1.0/data.length); 
    System.out.println(sum); 

} 

} 

雖然代碼運行良好,沒有錯誤,但它沒有給我我需要的輸出。平均應該是4

下面是一些編輯後的代碼:

public class AverageOfArray { 

public static void main(String []args){ 

    int [] data = new int[3]; 
    data[0] = 2; 
    data[1] = 4; 
    data[2] = 8; 


    double sum = 1.0; 

    for(int i = 0; i < data.length; i++){ 
     sum = sum * data[i]; 
    } 

    double geoMean = Math.pow(sum, 1.0/data.length); 
    System.out.println(geoMean); 

} 

} 

但是它現在返回3.9999996? 我現在在看Math.abs嗎?

回答

9

您的geometric mean計算錯誤。您必須將所有值相乘而不是添加它們。你的初始產品必須以1.0開頭。

double product = 1.0; 

後來......

product = product * data[i]; 

此外,中Math.pow結果存儲在一個新的變量 - 一個double,因爲這是Math.pow回報。

double geoMean = Math.pow(product, 1.0/data.length); 
+0

感謝您的反饋!我正在看這個。我正在研究另一個網站,他們在那裏使用加法! 謝謝。 – PrimalScientist 2013-05-08 21:21:36

+0

是的,現在明白了。我一直忘記捕獲我的輸出。謝謝!! – PrimalScientist 2013-05-08 21:23:56

+0

嗯,我的輸出是3.9999999999999996。 我需要Math.abs嗎? – PrimalScientist 2013-05-08 21:40:40

4
public static double geoMean(double[] arr) { 

    if (arr.length == 0) { 
     return 0.0; 
    } 

    double gm = 1.0; 
    for (int i = 0; i < arr.length; i++) { 
     gm *= arr[i]; 
    } 
    gm = Math.pow(gm, 1.0/(double) arr.length); 

    return gm; 
} 
+0

這很好,謝謝! =] – PrimalScientist 2013-05-08 21:21:56

+0

不客氣:) – 2013-05-08 21:27:06

1

您的代碼有幾個問題。首先,你需要乘以數值才能得到幾何平均值。然後,只需撥打Math.pow將不會更改該值;它會返回一個您必須捕獲的新值。例如:

sum = Math.pow(sum, 1.0/data.length); 
+0

啊,是的,我明白了。謝謝。 然後返回它,或者只是打印它。 – PrimalScientist 2013-05-08 21:22:35

+0

捕獲!是的,謝謝。 – PrimalScientist 2013-05-08 21:23:10

+0

感謝您的反饋泰德。 – PrimalScientist 2013-05-08 21:43:32

11

維基百科,https://en.wikipedia.org/wiki/Geometric_mean#Relationship_with_arithmetic_mean_of_logarithms,通常實現一個不同的(但當量)版本的幾何平均值公式。該版本使用對數來避免上溢和下溢。在Java中,它可能看起來像這樣:

class GeometricMean { 
    private GeometricMean() {} 

    public static void main(String[] args) { 
     long[] data = new long[]{2, 4, 8}; 
     double gm = geometricMean(data); 
     System.out.println("Geometric mean of 2, 4 and 8: " + gm); 
    } 

    public static double geometricMean(long[] x) { 
     int n = x.length; 
     double GM_log = 0.0d; 
     for (int i = 0; i < n; ++i) { 
      if (x[i] == 0L) { 
       return 0.0d; 
      } 
      GM_log += Math.log(x[i]); 
     } 
     return Math.exp(GM_log/n); 
    } 
} 
+0

感謝您的回答。我還沒有涉及Math.log或Math.exp呢! 雖然非常感謝! =] – PrimalScientist 2014-02-06 12:41:43