浮点值的字符串表示错误

时间:2015-03-19 21:22:19

标签: php factorial floating-point-conversion

我使用此功能计算阶乘:

function factorial($in) {
    // 0! = 1! = 1
    $out = 1;

    // Only if $in is >= 2
    for ($i = 2; $i <= $in; $i++) {
        $out *= $i;
    }

    return $out;
}

尝试将浮点值转换为某种bigint字符串表示形式。但从23开始!结果值不正确。输出是:

2.5852016738885E+22 <- this is the result (float)
25852016738884978212864 <- incorrect
25852016738884978212864 <- incorrect
25852016738884976640000 <- correct (used GMP library for calculation)

脚本本身:

<?php

//starting from 23 the result becomes incorrect if convert it to "integer string"
define('F_NUMBER', 23);

function factorial($in) {
    // 0! = 1! = 1
    $out = 1;

    // Only if $in is >= 2
    for ($i = 2; $i <= $in; $i++) {
        $out *= $i;
    }

    return $out;
}


$f = factorial(F_NUMBER);
echo "$f" . PHP_EOL; //The result as float
echo number_format($f, 0, '', '') . PHP_EOL; //Incorrect result
printf("%.0f" . PHP_EOL, $f); //Incorrect result
echo gmp_strval(gmp_fact(F_NUMBER)) . PHP_EOL; //Correct result

为什么会这样?没有GMP库,如何解决这个问题?

0 个答案:

没有答案