What is 0.14*300?

julia> 0.14*300
42.00000000000001

julia> Int32(0.14*300)
ERROR: InexactError: Int32(42.00000000000001)
Stacktrace:
 [1] Int32(x::Float64)
   @ Base .\float.jl:791
 [2] top-level scope
   @ REPL[12]:1

Or for that matter, it seems like 0.14 has a bug with floating point math …

julia> 0.14*50
7.000000000000001

julia> 0.14*100
14.000000000000002

julia> 0.14*40
5.6000000000000005

julia> 0.13*40
5.2

julia> 0.14*2203
308.42

julia> 0.14*10040
1405.6000000000001

julia> 0.14*200
28.000000000000004

This is a known limitation with float point operations. There might be some degree of imprecision because the computer does not represent numbers exactly. You will find similar results in Python for example.

1 Like

So is it safest to always use Int32(round( math )) if an integer is expected?

I suspect it depends on the amount of precision you need. You could use Int64 or BigInt if you need more precision. But I am not really an expert at mitigating float point rounding errors. I think if you describe your needs, someone with more expertise might be able to provide sound guidance.

1 Like

It seems like rational numbers might help with division, but that exhausts my knowledge.

1 Like

round(Int32, math) is better.

1 Like

For my error, it was just to go into an argument for an array initialization within a loop, e.g. zeros(Int32( x[i] * 300 )) and when x[i] was 0.14, it was not happy.

Gotcha. That might be OK if you are not testing exact equalities in your code. Perhaps you could isapprox, but there might be other or better options for such cases.

2 Likes