PHP:数学运算的精确性

时间:2013-07-04 16:20:47

标签: php rounding pow

我对PHP和数学运算有疑问。

为什么9000.05 - 9000返回0.049999999999272而不是0.05 ???

请看那个例子

function calculate ( $financed, $months, $rate){
    $installment = 782.90;  
    $rate= $rate / 100;
    $delta = 0;

    $OUT = $financed;
    $IN  = 0;

    for ($t = 1; $t <= $months; $t++){
        echo "installment $t \n";
        $installment_act =  $installment / pow((1 + ($rate / 12)), $t);
        $installment_act = round($installment_act, 2);
        echo "installment actualized $installment_act \n\n";
        $IN += $installment_act;
        echo "\t\t\t\t $IN\n";
    }
    echo "\n IN ($IN) - OUT ($OUT) = ";
    $delta = $IN - $OUT;
    echo "delta = $delta\n  ";
}

calculate(9000, 12, 8);

//RESULT

installment 1 
installment actualized 777.72 

                 777.72
installment 2 
installment actualized 772.56 

                 1550.28
installment 3 
installment actualized 767.45 

                 2317.73
installment 4 
installment actualized 762.37 

                 3080.1
installment 5 
installment actualized 757.32 

                 3837.42
installment 6 
installment actualized 752.3 

                 4589.72
installment 7 
installment actualized 747.32 

                 5337.04
installment 8 
installment actualized 742.37 

                 6079.41
installment 9 
installment actualized 737.45 

                 6816.86
installment 10 
installment actualized 732.57 

                 7549.43
installment 11 
installment actualized 727.72 

                 8277.15
installment 12 
installment actualized 722.9 

                 9000.05

IN (9000.05) - OUT (9000) = delta = 0.049999999999272

如你所见$ IN - $ OUT返回错误的结果,为什么?我怎么能解决它?

感谢提前任何建议 米歇尔

0 个答案:

没有答案