Most performant way to account for floating point errors?

I have a variable1 == variable2, but it returns false because they’re not the same:

image
(it’s supposed to be if 0.21 == 0.21 then)

Would it be more performant to round them, or to convert them to a string and shorten it?

Thanks!

Converting a float to a string is relatively slower. The typical way is to compare the absolute difference to some threshold:

if math.abs(variable1 - variable2) < 0.000001 then
--They are equal "enough"
end

This works, thank you!

May I ask you where you learn these small optimizations and how I can check if they worked or not, so I don’t have to ask this forum every time :sweat_smile:

Do you have a specific topic in mind? Any opinion I give on Lua performance will be controversial but all testable. See the “Profiling” section here: Proactive Testing: Profiling, Unit, and Fuzz testing

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.