PHP:使用此算法进行大值计算的问题

时间:2017-10-27 02:28:00

标签: php

嗨,我在运行映射计算的php中得到了这个功能。但似乎输出计算值完全不正确(1633375984562987776) - 期待(1633375984562987887)。这些大型数学计算需要某种特殊功能吗?关于我做错了什么的想法?

linktomediaid("Baq6s3Qh-Nv");
function linktomediaid($url) {
        $code = $url;
        echo "    USING CODE - '$url' \n"; 
        $alphabet = [
                '-' => 62, '1' => 53, '0' => 52, '3' => 55, '2' => 54, '5' => 57, '4' => 56, '7' => 59, '6' => 58, '9' => 61,
                '8' => 60, 'A' => 0, 'C' => 2, 'B' => 1, 'E' => 4, 'D' => 3, 'G' => 6, 'F' => 5, 'I' => 8, 'H' => 7,
                'K' => 10, 'J' => 9, 'M' => 12, 'L' => 11, 'O' => 14, 'N' => 13, 'Q' => 16, 'P' => 15, 'S' => 18, 'R' => 17,
                'U' => 20, 'T' => 19, 'W' => 22, 'V' => 21, 'Y' => 24, 'X' => 23, 'Z' => 25, '_' => 63, 'a' => 26, 'c' => 28,
                'b' => 27, 'e' => 30, 'd' => 29, 'g' => 32, 'f' => 31, 'i' => 34, 'h' => 33, 'k' => 36, 'j' => 35, 'm' => 38,
                'l' => 37, 'o' => 40, 'n' => 39, 'q' => 42, 'p' => 41, 's' => 44, 'r' => 43, 'u' => 46, 't' => 45, 'w' => 48,
                'v' => 47, 'y' => 50, 'x' => 49, 'z' => 51
            ];
        $n = 0;
        for ($i = 0; $i < strlen($code); $i++) {
            $c = $code[$i];
        $n = $n * 64 + $alphabet[$c];
            echo "    n calculation value - $n\n";
        }
        $newvalue = sprintf ("%.0f", $n);
        echo "    final n value - $newvalue\n";
        return $n;
    }

这是我在终端中看到的输出:

USING CODE - 'Baq6s3Qh-Nv'
    n calculation value - 1
    n calculation value - 90
    n calculation value - 5802
    n calculation value - 371386
    n calculation value - 23768748
    n calculation value - 1521199927
    n calculation value - 97356795344
    n calculation value - 6230834902049
    n calculation value - 3.987734337312E+14
    n calculation value - 2.5521499758797E+16
    n calculation value - 1.633375984563E+18
    final n value - 1633375984562987776

1 个答案:

答案 0 :(得分:3)

您将非常接近PHP中存储的最大值。您可能正在经历溢出。当您超过PHP的限制时,它将自动切换到浮点数:

  

如果PHP遇到超出整数类型边界的数字,则会将其解释为float。此外,导致超出整数类型边界的数字的操作将返回浮点数。

Floating point numbers一个不完全精确的,这就是为什么它们允许你如此大范围。您的计算可能超过最大整数值,因此它开始使用浮点运算,因此精度丢失。