2017-03-27 22 views
0
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個數字後變得不準確。這似乎是一個相當隨意的數字,所以我想不出爲什麼它會像其他溢出一樣錯誤。

任何人都知道爲什麼?

回答

3

這很可能是溢出,因爲斐波納契數字呈指數增長。

在Lua 5.3之前,Lua中的所有數字都是雙精度浮點數。這意味着最多可以表示52位的整數。事實上,F(78)= 8944394323791464可以完全表示,但F(79)= 14472334024676221不能。

在具有64位整數的Lua 5.3中,可以精確地表示直到F(92)= 754011380474634642的斐波那契數。