[Pharo-dev] float & fraction equality bug
martin at hand2mouse.com
Thu Nov 9 09:34:40 EST 2017
On 11/09/2017 06:15 AM, Tudor Girba wrote:
> I just stumbled across this bug related to the equality between
> fraction and float:
> In essence, the problem can be seen that by doing this, you get a
> x := 0.1.
> y := (1/10).
> x = y ifFalse: [ 1 / (x - y) ]
> The issue seems to come from the Float being turned to a Fraction,
> rather than the Fraction being turned into a Float:
> Fraction(Number)>>adaptToFloat: rcvr andCompare: selector
> "If I am involved in comparison with a Float, convert rcvr to a
> Fraction. This way, no bit is lost and comparison is exact."
> rcvr isFinite
> ifFalse: [
> selector == #= ifTrue: [^false].
> selector == #~= ifTrue: [^true].
> rcvr isNaN ifTrue: [^ false].
> (selector = #< or: [selector = #'<='])
> ifTrue: [^ rcvr positive not].
> (selector = #> or: [selector = #'>='])
> ifTrue: [^ rcvr positive].
> ^self error: 'unknow comparison selector'].
> ^ *rcvr asTrueFraction perform: selector with: self*
> Even if the comment says that the comparison is exact, to me this is a
> bug because it seems to fail doing that. What do you think?
I think exact comparison is the best thing to do here (even though ANSI
says otherwise). And an exact comparison will answer false, because
there is no float that is exactly equal to 1/10 -- it is an infinitely
repeating decimal in binary.
For consistency, though, it might be better to compute x - y by
converting the Float to a Fraction rather than the other way around
(though this would also contravene ANSI) since Fraction is the more
general format (every Float can be represented exactly as a Fraction,
but the reverse is not true).
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Pharo-dev