How is Lua floating point processing different from other languages?

When I execute 0.1 + 0.2 in Lua, I definitely get 0.3 . If I do the same in Ruby or Python, for example, I get 0.30000000000000004 . I understand floating point rounding errors, but why does this problem not occur in Lua? What makes Lua different?

+4
source share
1 answer

0.1+0.2 definitely not 0.3 . Try this code:

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

I assume that you are using print or io.write to print these values. In this case, Lua just does not print all the numbers. Internally, Lua uses a full-size, native floating-point representation. The technical explanation is that the print and io.write format io.write are used in the LUA_NUMBER_FMT format defined in luaconf.h , which defaults to "%.14g" .

+8
source

Source: https://habr.com/ru/post/1494839/


All Articles