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