Large numbers multiplication

Hello everyone,

Im doing some concentration conversion and I noticed this issue.

julia> 3.321155762205247e-10 * 6.022e23 * 0.5e-3 * 1e-6
100000.0

now if I put last three numbers in a variable.

x = 6.022e23 * 0.5e-3 * 1e-6

and Then multiply

julia> 3.321155762205247e-10 * x
99999.99999999999

Can someone tell me whats going on ? Like I know its almost same thing but I’m curious why?

Thank you :slight_smile:

julia> 3.321155762205247e-10 * 6.022e23 * 0.5e-3 * 1e-6
100000.0

julia> 3.321155762205247e-10 * ( 6.022e23 * 0.5e-3 * 1e-6 )
99999.99999999999

It’s about floating point numbers and how they are represented in binary machines.
Last time we had this was here: Mismatch between nextfloat(0.0) and eps(Float64)

8 Likes

In particular, because every floating-point operation potentially incurs a rounding operation (to the closest representable number), floating-point operations like multiplication and addition are not associative.

This is true in every programming language, not just Julia; it’s intrinsic to fp arithmetic.

8 Likes