Why am I getting the wrong results for these simple operations in Julia?

I started using the Julia language, but I am surprised to get seemingly incorrect results even with basic operations:

julia> 0.05*0.05
0.0025000000000000005

and

julia> 1.0-0.85-0.1
0.05000000000000002

How can it be? And what can I do to get accurate results?

0
source share
1 answer

I am surprised to receive seemingly incorrect results even with basic operations [...] How can this be?

The IEEE-754 binary floating-point numbers ( which Julia uses ) cannot represent numbers exactly, such as 0.05, 0.85, and 0.1.

, 0.05 Julia, , , , 0,05, 0,05. , , 0.05*0.05, 0,0025.

?

julia> 1-0.2-0.2-0.2-0.2-0.2
5.551115123125783e-17

julia> 0.6/0.2 == 3
false

( !), . TeX.


?

? , , Julia , , .

, , Rational{Int64}, , 64- . ( ) :

julia> 1//20 * 1//20
1//400

julia> 1 - 17//20 - 1//10
1//20

, arbitrary-precision , Rational{BigInt} (. - )

+10

Source: https://habr.com/ru/post/1609730/


All Articles