整數域

lua-users home
Wiki

下列程式碼計算 Lua 可以精確表示的整數數字實際界線(雙精度浮點數字)- 除此之外,這是「連續近似」技巧的一個好範例

--**** 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)

--AndreasRozek


正確性可以證明嗎?它有採用 IEEE 嗎?--DavidManura

嗯,讓我思考一下需求

此外,我還做了其他兩個假設

兩個假設都可以在明確的情況下輕鬆查驗(測試負數時,別忘了將「floor」替換為「ceil」!)。

如果需求適用,則可以使用「連續近似」取得最大的可呈現整數。

由於我未提及任何具體結果,因此,除了上述假設(符號幅度編碼保證對稱性)和我所選擇的測試之外,我並未真正採用 IEEE

--AndreasRozek

---- 我以 lua 5.1 執行此演算法,但並未完全正常運作:它將「9007199254740994」當成最大整數,但 print(string.format("%0.f", intlimit()-1) 返回「9007199254740992」而非「9007199254740993」。我在程式碼中修正了三件事

--4xel


近期變動 · 喜好設定
編輯 · 歷史
最後編輯於 2016 年 4 月 15 日下午 6:54 GMT (diff)