# Calculating ULP distance between two floating point numbers (quickly)

**URL:** <https://discourse.julialang.org/t/calculating-ulp-distance-between-two-floating-point-numbers-quickly/61581>\
**Category:** General Usage\
**Tags:** float\
**Created:** [May 21, 2021, 11:48am UTC](https://discourse.julialang.org/t/calculating-ulp-distance-between-two-floating-point-numbers-quickly/61581 "2021-05-21T11:48:19Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![Sukera](https://avatars.discourse-cdn.com/v4/letter/s/ce7236/32.png) [@Sukera](https://discourse.julialang.org/u/Sukera)\
**Post date:** [May 21, 2021, 12:26pm UTC](https://discourse.julialang.org/t/calculating-ulp-distance-between-two-floating-point-numbers-quickly/61581/3 "2021-05-21T12:26:17Z")

</div>

> [@fellbyyourgun](#):
>
> I need to compare floating point numbers for near-equality.

Is using `isapprox` an option? You can give it an absolute or relative allowed difference.

In case it isn’t, the code from your link would look like this in julia:

```julia
function ulpsBetween(a::Float64, b::Float64)
    a == b && return 0
    isnan(a) || isnan(b) && return typemax(Int)
    isinf(a) || isinf(b) && return typemax(Int)
    
    a_int = reinterpret(Int64, a)
    b_int = reinterpret(Int64, b)

    (a_int < 0) != (b_int < 0) && return typemax(Int)

    return abs(a_int - b_int)
end

```

Still, the link discusses precisely why this sort of comparison usually isn’t a good idea (and `isapprox` is usually the best choice anyway). It’s implemented like this:

```julia
function isapprox(x::Number, y::Number;                                                                                          
                  atol::Real=0, rtol::Real=rtoldefault(x,y,atol),                                                                
                  nans::Bool=false, norm::Function=abs)                                                                          
    x == y || (isfinite(x) && isfinite(y) && norm(x-y) <= max(atol, rtol*max(norm(x), norm(y)))) || (nans && isnan(x) && isnan(y)
end                                                                                                                              

```

which you can find via `@edit isapprox(0.5, 1.0)` at `base/floatfuncs.jl:360`.

---

_[View the full topic](https://discourse.julialang.org/t/calculating-ulp-distance-between-two-floating-point-numbers-quickly/61581)._
