Set default tolerance for isapprox()

How can I define isapprox() for a type such that I can set a default tolerance but the user can override it if required?

struct MyType
	 v::Float64
end

Base.isapprox(x::MyType, y::MyType) = isapprox(x.v, y.v, atol=10e-6)

x = MyType(10.0 / 3)
y = MyType(3.33)

@show isapprox(x, y) # usually false with 10e-6

@show isapprox(x, y, atol = 10e-12) # can be true if required

I think it’s something with kwargs ? but I forget how it’s done.

Your implementation can pass along all keywords like this:

Base.isapprox(x::MyType, y::MyType; kwargs...) = isapprox(x.v, y.v; kwargs...)
1 Like

Thanks - where do I put the default 10e-6 though?

Ah, I misunderstood. You can capture a specific kwarg like this for example:

function Base.isapprox(x::MyType, y::MyType; atol=nothing, kwargs...)
    if atol === nothing
        atol = 1e-6
    end
    return isapprox(x.v, y.v; atol=atol, kwargs...)
end
2 Likes

Ah, great, thanks! I get confused with the kwargs stuff.

Anything wrong with the following?

function Base.isapprox(x::MyType, y::MyType; atol=1e-6, kwargs...)
    return isapprox(x.v, y.v; atol=atol, kwargs...)
end
2 Likes

No not in this simple case. I was thinking of the case when you need to differentiate between “user has passed atol” and “user has not passed atol”.

2 Likes