Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

julia floating point compare for zero

Tags:

julia

julia> r
3×3 Array{Float64,2}:
 -1.77951  -0.79521   -2.57472
  0.0       0.630793   0.630793
  0.0       0.0       -1.66533e-16

julia> sort(abs(diag(r)))[1]
1.6653345369377348e-16

julia> isequal(floor(sort(abs(diag(r)))[1]),0)
true

But this is not right

julia> isequal(sort(abs(diag(r)))[1],convert(AbstractFloat,0.0))
false

Is there a function in Julia to check for floating point equivalent to zero?

like image 368
Userdijkstra Avatar asked Mar 09 '23 16:03

Userdijkstra


1 Answers

-1.66533e-16 is not equivalent to zero. It is, however, approximately equivalent to zero (with respect to a particular tolerance), and julia does provide just such a function:

isapprox(1e-16, 0.0; atol=1e-15, rtol=0)

edit: or as Chris pointed out, a good choice for atol is eps() which corresponds to machine precision for that particular type:

julia> isapprox(1e-20, 0.0; atol=eps(Float64), rtol=0)
true

Do read the description for isapprox to see what the default arguments mean, and to see if you prefer an "absolute" or "relative" tolerance approach (or a mixed approach). Though for a comparison to zero specifically, using an absolute tolerance is fine and probably more intuitive.

like image 177
Tasos Papastylianou Avatar answered Mar 15 '23 15:03

Tasos Papastylianou