[Pharo-dev] float & fraction equality bug

Sven Van Caekenberghe sven at stfx.eu
Thu Nov 9 09:35:09 EST 2017

```Doru,

1/10 cannot be represented as Float without loss of precision. So even though (1/10) asFloat gives you 0.1, the reverse is not possible.

Floating point is a binary (as in base 2 representation), not a decimal (base 10) representation.

Consider

(1/8) asFloat asTrueFraction.

which is reversible.

x := 0.125.
y := (1/8).
x = y ifFalse: [ 1 / (x - y) ].

You can see that a bit in the binary representation view:

Sven

> On 9 Nov 2017, at 15:15, Tudor Girba <tudor at tudorgirba.com> wrote:
>
> Hi,
>
> I just stumbled across this bug related to the equality between fraction and float:
> https://pharo.fogbugz.com/f/cases/20488/x-y-iff-x-y-0-is-not-preserved-in-Pharo
>
> In essence, the problem can be seen that by doing this, you get a ZeroDivide:
> 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:
>
> 	"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?
>
> Cheers,
> Doru
>
>
> --
> www.tudorgirba.com
> www.feenk.com
>
> "Problem solving should be focused on describing
> the problem in a way that makes the solution obvious."
>
>
>
>
>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.pharo.org/pipermail/pharo-dev_lists.pharo.org/attachments/20171109/64203efb/attachment-0002.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: Screen Shot 2017-11-09 at 15.33.00.png
Type: image/png
Size: 75216 bytes
Desc: not available
URL: <http://lists.pharo.org/pipermail/pharo-dev_lists.pharo.org/attachments/20171109/64203efb/attachment.png>
```