close

  拜重拾三年前的專案所賜,其所需要的Know how基於統計學、線性代數,乃至更高層次的作業研究(Operator Research),大陸稱之運籌學(取得不錯,運籌惟幄之中,決勝千里之外)。而Apache的commons-math套件也提供相當的函數,如幾何平均數:

43cea9aee871f9ad5ec664fcf4f9e2e3

  可以引用package org.apache.commons.math.stat.descriptive.moment.GeometricMean,並用下面方式求得

GeometricMean geoMean = new GeometricMean();
System.out.println( "geometric mean: " + geoMean.evaluate( new double[] { 2.3, 5.4, 6.2, 7.3, 23.3 } ) );

  而標準差則為org.apache.commons.math.stat.descriptive.moment.StandardDeviation,也是用evaluate method求得。

6336e4c48fd253b7a6f552fa2579525b 只是統計學上有母體標準差和樣本標準差之分,不知在commons-math是否也有對映提供。

  commons-math 2.0到2009年八月釋出,有好幾個class和method被標為deprecated(不建議使用)。其中聯立方程式在2.0版提供的解法最是奇怪。

第一、建議Array2DRowRealMatrix取代RealMatrixImpl,這個沒什麼問題,兩個class同樣實作RealMatrix介面。

第二、RealMatrix的solve method被標為deprecated。取而代之要用實作DecompositionSolver介面的instance的solve方法,而目前DecompositionSolver的實作品只有LUDecompositionImpl,LU是一個數學方法。若是有解的聯立方程式,不管新舊都沒問題,但若聯立方程式無解,用RealMatrix的solve會丟出以下的Exception:

org.apache.commons.math.linear.SingularMatrixException: matrix is singular

  但若用LUDecompositionImpl的solve,不會丟出Exception,解出來的值根本也錯。很納悶為什麼要標這些deprecated。其聯立方式程用法如下,取材自O'Reilly的Jakarta commons cookbook:

數學式為:

3x + 20y + 89z = 1324
4x + 40y + 298z = 2999
7x - 21y + 0.42z = 2039

程式碼如下:

double[][] coefficients = { { 3.0, 20.0, 89.0 },
            { 4.0, 40.0, 298.0 },
            { 7.0, 21.0, 0.42 } };
double[] values = new double[] { 1324, 2999, 2039 };

RealMatrix matrix = new Array2DRowRealMatrix( coefficients );

double[] answers = matrix.solve( values );  // 舊的解法
System.out.println( "Old X, Y, Z: " + ArrayUtils.toString( answers ) );

DecompositionSolver solver = new LUDecompositionImpl(matrix).getSolver(); // 新解法
answers = solver.solve(values);

System.out.println( "New X, Y, Z: " + ArrayUtils.toString( answers ) );

若然數學式為

1x + 1y + 1z = 0
1x + 1y + 1z = 1
1x + 1y + 1z = 3

則用deprecated solve會丟出Exception,用LD就得到很OOXX的值。

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Jemmy 的頭像
    Jemmy

    Jemmy Walker

    Jemmy 發表在 痞客邦 留言(0) 人氣()