lua-users home
lua-l archive

Re: Float numbers equality.

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


On Fri, Aug 9, 2013 at 12:37 PM, Matthias Kluwe <mkluwe@gmail.com> wrote:
> Hi!
>
> 2013年8月9日 Karol Dro <karoldro@gmail.com>:
>
>> 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?
>
> In short: Use a reasonable "epsilon".
Slightly longer "in short" -- this means use something like:
function float_equal(lhs, rhs, epsilon)
 return math.abs(lhs - rhs) < epsilon
end
/s/ Adam

AltStyle によって変換されたページ (->オリジナル) /