问题描述
- java 与 php 计算结果的差异
-
计算矩阵权重的一个方法
输入的矩阵都是
{ 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.权重的计算结果到小数点后第三位就不一样了。
这种误差属于正常吗?
误差产生的原因是不是与浮点数的计算有关?
解决方案
weights[i] = Math.pow(weights[i], (double)1/weights.length);
weights[i] = Math.pow(weights[i], (double)1/(double)weights.length);
否则是整除
别的一样修改
解决方案二:
从c++到Java 之一(47个差异)