【问题标题】:How to deal with the problem of insufficient precision of lua floating point numbers [duplicate]lua浮点数精度不够怎么处理[重复]
【发布时间】:2021-11-03 23:04:10
【问题描述】:

在使用 lua 处理浮点数时,我发现 lua 可以处理非常有限的精度,例如:

print(3.14159265358979)

输出:

3.1415926535898

结果会少几位小数,导致计算偏差。我该如何处理这种缺乏精度的问题

【问题讨论】:

  • 您可以了解 LUA here 中数字的表示方式。 this question 有一些关于 LUA 模块提示的答案,可以让您更精确地使用数字。
  • print(("%.17g"):format(3.14159265358979))
  • "精度非常有限" 我不会将 12 位小数称为“精度非常有限”。

标签: lua


【解决方案1】:

默认情况下,Lua 只显示 14 位数字。浮点数可能需要 15 到 17 位数字才能完全表示为 base-10 字符串。我们可以使用循环来找到正确的位数。请注意,%g 将删除尾随零,因此我们可以从 15 位而不是 1 位开始搜索。这是我使用的函数:

local function floatToString(x)
  for precision = 15, 17 do
    -- Use a 2-layer format to try different precisions with %g.
    local s <const> = ('%%.%dg'):format(precision):format(x)
    -- See if s is an exact representation of x.
    if tonumber(s) == x then
      return s
    end
  end
end

print(floatToString(3.14159265358979))

输出:3.14159265358979

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-26
    • 2022-01-22
    • 2010-10-10
    • 1970-01-01
    • 2013-01-03
    • 2021-09-16
    • 2011-02-23
    相关资源
    最近更新 更多