matrix-java 與 php 計算結果的差異

來源:互聯網
上載者:User
關鍵字 matrix php java 函數
matrixphpjava函數

計算矩陣權重的一個方法
輸入的矩陣都是
{ 0,2, 6, 1,-7},
{-2,0,-5, 0,-5}
{-6,5, 0, 8, 1}
{-1,0,-8, 0, 7}
{ 7,5,-1,-7, 0}

這是java的計算代碼
static double[] weights=new double weights[5];
private double computeCIandWeights(int[][] matrix) {
double totalWeight = 0;
for (int i = 0; i < weights.length; i++) {
weights[i] = 1;
for (int j = 0; j < weights.length; j++)
weights[i] *= decode(matrix[i][j]);
weights[i] = Math.pow(weights[i], (double)1/weights.length);
totalWeight += weights[i];
}
for (int i = 0; i < weights.length; i++)
weights[i] /= totalWeight;
double eig = 0;
for (int i = 0; i < weights.length; i++) {
double part = 0;
for (int j = 0; j < weights.length; j++)
part += decode(matrix[i][j])*weights[j];
part /= weights[i]*weights.length;
eig += part;
}
return (eig-weights.length)/(weights.length-1);
}

    private double decode(int num) {        if (num < 0)            return (double)1/(1-num);        else            return num+1;    }    然後結果是

CI=0.097302165775079
weights:0.10850015438106028
weights:0.056125161448460546
weights:0.45493710163432743
weights:0.06991685010726335
weights:0.3105207324288884
------------------------------------------------------------------------------------
這是php的計算代碼

function computeCIandWeights($matrix,&$weights){
$totalWeight=0.0;
$len=5;
for($i=0;$i<$len;$i++){
$weights[$i]=1;
for($j=0;$j<$len;$j++){
$weights[$i]*=decode($matrix[$i][$j]);
}
$weights[$i]=pow($weights[$i],doubleval(1/$len));
$totalWeight +=doubleval($weights[$i]);
}
for($i=0;$i<$len;$i++){
$weights[$i]/=$totalWeight;
}
$eig=0.0;
for($i=0;$i<$len;$i++){
$part=0.0;
for ($j=0;$j<$len;$j++){
$part+=decode($matrix[$i][$j])*$weights[$j];
}
$part/=$weights[$i]*$len;
$eig+=$part;
}
return ($eig-$len)/($len-1);
}
function decode($num){
if($num<0){
return doubleval(1/(1-$num));
}else{
return $num+1;
}
}

$ci=computeCIandWeights($inputMatrix, $weights);
echo 'ci='.$ci.'.
';
for($i=0;$i echo 'weights='.$weights[$i].'.
';
}

結果是
ci=0.0973021657751.
weights=0.106290974412.
weights=0.0549823927295.
weights=0.445674092399.
weights=0.0631581840822.
weights=0.329894356377.

權重的計算結果到小數點後第三位就不一樣了。
這種誤差屬於正常嗎?
誤差產生的原因是不是與浮點數的計算有關?

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.