在任意点精度出现问题

target="/home/walia6/Math/fib"
os.execute("echo 1 > "..target)
os.execute("echo 1 >> "..target)
while true do
    local handle = io.popen("wc -l < "..target)
    ct = handle:read("*a")
    handle:close()
    os.execute("echo "..ct)

    tmp=("sed -n "..(ct-1).."p "..target)
    --os.execute("echo '"..tmp.."'")
    local handle = io.popen(tmp)
    pn = handle:read("*a")
    handle:close()

    tmp=("sed -n "..(ct-0).."p "..target)
    --os.execute("echo '"..tmp.."'")
    local handle = io.popen(tmp)
    cn = handle:read("*a")
    handle:close()

    os.execute("echo "..(string.format("%.0f",cn+pn)).." >>"..target)
end

上面是我在Linux中使用Lua进行实验时编写的一些代码。我更多的是在测试Linux而不是在测试Lua。

然而,我注意到,在生成的第78个数字之后,我的斐波那契数列生成器变得不准确了。这似乎是一个相当任意的数字,所以我无法想象为什么会出现错误,除非是某种溢出。

有人知道是为什么吗?

点赞
用户107090
用户107090

因为斐波那契数列的增长是指数级别的,所以最有可能是溢出现象。

Lua 5.3 之前,Lua 中所有数字都是双精度浮点数。这意味着可以精确表示最多 52 位的整数。实际上,F(78) = 8944394323791464 可以精确表示,但 F(79) = 14472334024676221 不行。

在 Lua 5.3 中,有 64 位整数,可以精确表示斐波那契数列直到 F(92) = 754011380474634642。

2017-03-28 01:04:22