整數域 |
|
--**** should be compatible with 5.xx function intlimit() local floor = math.floor -- get highest power of 2 which Lua can still handle as integer local step = 2 while true do local nextstep = step*2 if nextstep-(nextstep-1) == 1 and nextstep > 0 then step = nextstep else break end end -- now get the highest number which Lua can still handle as integer local limit,step = step,floor(step/2) while step > 0 do local nextlimit = limit+step if nextlimit-(nextlimit-1) == 1 and nextlimit > 0 then limit = nextlimit end step = floor(step/2) end return limit end
範例
local limit = intlimit() print() print("IntegerDomain - what is the largest supported integer number?") print() --**** do not rely on Lua to print "limit" properly by itself! --local printablelimit = string.format("%d", limit) -- fails under Lua! local printablelimit = string.format("%.16e", limit) print("supported integer range is: -" .. printablelimit .. "...+" .. printablelimit)
如你所見,Lua 可以處理大型整數數字而不會有任何問題,只要你別嘗試將它們轉換成字串即可 ;-)
為確保整數數字正確轉換成字串(不使用科學符號),請使用 format.string("%.0f",x),而非 tostring(x)
嗯,讓我思考一下需求
此外,我還做了其他兩個假設
兩個假設都可以在明確的情況下輕鬆查驗(測試負數時,別忘了將「floor」替換為「ceil」!)。
如果需求適用,則可以使用「連續近似」取得最大的可呈現整數。
由於我未提及任何具體結果,因此,除了上述假設(符號幅度編碼保證對稱性)和我所選擇的測試之外,我並未真正採用 IEEE
floor(x) == x
應該已經足夠用於測試數字是否為整數x-1 ~= x
剛剛已新增,用於排除 NaN 和無窮大---- 我以 lua 5.1 執行此演算法,但並未完全正常運作:它將「9007199254740994」當成最大整數,但 print(string.format("%0.f", intlimit()-1) 返回「9007199254740992」而非「9007199254740993」。我在程式碼中修正了三件事
floor(x) == x
沒用,因為你從整數開始,而且執行整數穩定運算,即使超過最大整數(能夠表示的尾數比浮動數字大的浮點數字永遠都是整數)x-1 ~= x
已改為 x-(x-1) == 1
,它會檢查 x-1 是否也為可呈現數字(它也會排除 NaN 和無窮大,但它們無論如何都無法到達)x > 0
--4xel