Home >Backend Development >PHP Tutorial >matrix-java 与 php 计算结果的差异

matrix-java 与 php 计算结果的差异

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-02 11:31:04877browse

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[i] = 1;
for (int j = 0; 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[i] /= totalWeight;
double eig = 0;
for (int i = 0; i double part = 0;
for (int j = 0; j part += decode(matrix[i][j])*weights[j];
part /= weights[i]*weights.length;
eig += part;
}
return (eig-weights.length)/(weights.length-1);
}

<code>    private double decode(int num) {        if (num </code>

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 $weights[$i]=1;
for($j=0;$j $weights[$i]*=decode($matrix[$i][$j]);
}
$weights[$i]=pow($weights[$i],doubleval(1/$len));
$totalWeight +=doubleval($weights[$i]);
}
for($i=0;$i $weights[$i]/=$totalWeight;
}
$eig=0.0;
for($i=0;$i $part=0.0;
for ($j=0;$j $part+=decode($matrix[$i][$j])*$weights[$j];
}
$part/=$weights[$i]*$len;
$eig+=$part;
}
return ($eig-$len)/($len-1);
}
function decode($num){
if($num 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.

权重的计算结果到小数点后第三位就不一样了。
这种误差属于正常吗?
误差产生的原因是不是与浮点数的计算有关?

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn