Skip to content

Instantly share code, notes, and snippets.

@jgoizueta
Created March 28, 2017 13:15
Show Gist options
  • Save jgoizueta/febaec102067d9d9a628b1d1f6da0e4e to your computer and use it in GitHub Desktop.
Save jgoizueta/febaec102067d9d9a628b1d1f6da0e4e to your computer and use it in GitHub Desktop.
Floating Point Fun

Floating point unexpected results demo

Save for the last case (a poor try at showing floating point equality isn't reflexive), these examples seem specially surprising due to the base-conversion involved (since input is decimal and the floating point numbers used are binary), which hides the actual number of significant digits involved in each case.

Python

python
>>> 0.1 + 0.2 == 0.3
False
>>> 1E19*1E-20 == 1E-1
False
>>> 0.1+(0.2+0.3) == (0.1+0.2)+0.3
False
>>> 0.1+0.2+0.3 == 0.3+0.2+0.1
False
>>> 100*(0.1 + 0.2) == 100*0.1 + 100*0.2
False

>>> import numpy
>>> numpy.float64(0.0)/numpy.float64(0.0) == numpy.float64(0.0)/numpy.float64(0.0)
False

Ruby

irb
irb(main):001:0> 0.1 + 0.2 == 0.3
=> false
irb(main):002:0> 1E19*1E-20 == 1E-1
=> false
irb(main):003:0> 0.1+(0.2+0.3) == (0.1+0.2)+0.3
=> false
irb(main):004:0> 0.1+0.2+0.3 == 0.3+0.2+0.1
=> false
irb(main):005:0> 100*(0.1 + 0.2) == 100*0.1 + 100*0.2
=> false
irb(main):006:0> 0.0/0 == 0.0/0
=> false

Julia

julia> 0.1 + 0.2 == 0.3
false

julia> 1E19*1E-20 == 1E-1
false

julia> 0.1+(0.2+0.3) == (0.1+0.2)+0.3
false

julia> 0.1+0.2+0.3 == 0.3+0.2+0.1
false

julia> 100*(0.1 + 0.2) == 100*0.1 + 100*0.2
false

julia> 0.0/0 == 0.0/0
false

JavaScript (Node)

>  0.1 + 0.2 == 0.3
false
>  1E19*1E-20 == 1E-1
false
>  0.1+(0.2+0.3) == (0.1+0.2)+0.3
false
>  0.1+0.2+0.3 == 0.3+0.2+0.1
false
> 100*(0.1 + 0.2) == 100*0.1 + 100*0.2
false
> 0/0 == 0/0
false

R

> 0.1 + 0.2 == 0.3
[1] FALSE
> 1E19*1E-20 == 1E-1
[1] FALSE
> 0.1+(0.2+0.3) == (0.1+0.2)+0.3
[1] FALSE
> 0.1+0.2+0.3 == 0.3+0.2+0.1
[1] FALSE
> 100*(0.1 + 0.2) == 100*0.1 + 100*0.2
[1] FALSE
> 0.0/0 == 0.0/0
[1] NA
>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment