Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Lua's floating-point handling differ from other languages?

When I execute 0.1 + 0.2 in Lua, I get 0.3 exactly. If I do the same in Ruby or Python for example, I get 0.30000000000000004. I understand floating-point rounding errors, but why doesn't this problem occur in Lua? What does Lua do differently?

like image 488
user2643805 Avatar asked Feb 16 '23 16:02

user2643805


1 Answers

0.1+0.2 is not 0.3 exactly. Try this code:

print((0.1+0.2)==0.3)
print(string.format("%.17g",0.1+0.2))

I assume you're using print or io.write to print those values. In this case, Lua is just not printing all digits. Internally, Lua uses full-length, native floating-point representation. The technical explanation is that print and io.write format numbers using the format in LUA_NUMBER_FMT defined in luaconf.h, which by default is "%.14g".

like image 64
lhf Avatar answered May 08 '23 23:05

lhf