如何处理lua个浮点数精度不够的问题
How to deal with the problem of insufficient precision of lua floating point numbers
当使用lua处理浮点数时我发现lua可以处理非常有限的精度,例如:
print(3.14159265358979)
输出:
3.1415926535898
结果会少小数位,导致计算偏差。我该如何处理这种缺乏精度的问题
默认情况下,Lua 只显示 14 位数字。浮点数可能需要 15 到 17 位数字才能精确表示为以 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
当使用lua处理浮点数时我发现lua可以处理非常有限的精度,例如:
print(3.14159265358979)
输出:
3.1415926535898
结果会少小数位,导致计算偏差。我该如何处理这种缺乏精度的问题
默认情况下,Lua 只显示 14 位数字。浮点数可能需要 15 到 17 位数字才能精确表示为以 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