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?
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With