lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]




On Friday, August 9, 2013, Karol Dro wrote:
Hi,

I'm writing some unit tests, where I compare numbers and I have problem with something like this: 
300 * 0.07 == 21 => false.
print (300 * 0.07, 21, 300 * 0.07 == 21)

What is the best way, for test float equality?

I consider to use tostring function:
print (300 * 0.07, 21, tostring (300 * 0.07) == tostring (21)),
But i wonder, maybe there is a better way, to compare something like this?

Thanks for any response.

--
Karol Drożak

This is exactly the problem that I've been working with. My first attempt was to do it is to do the calculation in the same way as I did in the function, but that created a tight coupling. 

The format("%.10f", x) method was the most reasonable, for my testing needs, because it allowed me to specify the precision that I needed.

In the end, floats were too challenging to work with because my conversions were being rounded down or up, depending upon where the conversion was coming from and the size of the values.

I decided to go with integers by using Luiz's lint64 package. I keep multiplying everything as long as possible and then deal with division at the last step. I mod the division if I need to know what the partial portion of the sample is. 

I don't know your specific case and others made my same suggestion. I just couldn't help but chime in, given this has been my life for the last few days. :)

-Andrew