I want to find the number which act to 0 of Julia - I mean the nearest number of 0

Viewed 140

Why does this happen in Julia?

My input is

A = []
for i = 17:21
    t = 1/(10^(i))
    push!(A, t)
end
return(A)

And the output was:

5-element Array{Any,1}:
  1.0e-17
  1.0e-18
 -1.1838881245526248e-19
  1.2876178137472069e-19
  2.5800991659088344e-19

I observed that

A[3]>0
false

I want to find the number which act to 0 of Julia, but I found this and don’t understand.

1 Answers

The reason for this problem is when you have i = 19, note that then:

julia> 10^19
-8446744073709551616

and it is unrelated to floating point numbers, but is caused by Int64 overflow.

Here is the code that will work as you expect. Either use 10.0 instead of 10 as 10.0 is a Float64 value:

julia> A=[]
Any[]

julia> for i=17:21
       t=1/(10.0^(i))
       push!(A,t)
       end

julia> A
5-element Array{Any,1}:
 1.0e-17
 1.0e-18
 1.0e-19
 1.0e-20
 1.0e-21

or using high precision BigInt type that is created using big(10)

julia> A=[]
Any[]

julia> for i=17:21
       t=1/(big(10)^(i))
       push!(A,t)
       end

julia> A
5-element Array{Any,1}:
 9.999999999999999999999999999999999999999999999999999999999999999999999999999967e-18
 9.999999999999999999999999999999999999999999999999999999999999999999999999999997e-19
 9.999999999999999999999999999999999999999999999999999999999999999999999999999997e-20
 1.000000000000000000000000000000000000000000000000000000000000000000000000000004e-20
 9.999999999999999999999999999999999999999999999999999999999999999999999999999927e-22

You can find more discussion of this here https://docs.julialang.org/en/v1/manual/integers-and-floating-point-numbers/#Overflow-behavior.

For example notice that (which you might find surprising not knowing about the overflow):

julia> x = typemin(Int64)
-9223372036854775808

julia> x^2
0

julia> y = typemax(Int64)
9223372036854775807

julia> y^2
1

Finally to find smallest positive Float64 number use:

julia> nextfloat(0.0)
5.0e-324

or

julia> eps(0.0)
5.0e-324
Related