Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add generic fallback to all scalar functions #71

Merged
merged 2 commits into from
Jan 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions src/NaNMath.jl
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,20 @@
($f)(x::Float64) = ccall(($(string(f)),libm), Float64, (Float64,), x)
($f)(x::Float32) = ccall(($(string(f,"f")),libm), Float32, (Float32,), x)
($f)(x::Real) = ($f)(float(x))
if $f !== :lgamma
($f)(x) = (Base.$f)(x)
end
end
end

for f in (:sqrt,)
@eval ($f)(x) = (Base.$f)(x)
end

for f in (:max, :min)
@eval ($f)(x, y) = (Base.$f)(x, y)
end

# Would be more efficient to remove the domain check in Base.sqrt(),
# but this doesn't seem easy to do.
sqrt(x::T) where {T<:AbstractFloat} = x < 0.0 ? T(NaN) : Base.sqrt(x)
Expand All @@ -22,11 +33,13 @@
pow(x::Float32, y::Float32) = ccall((:powf,libm), Float32, (Float32,Float32), x, y)
# We `promote` first before converting to floating pointing numbers to ensure that
# e.g. `pow(::Float32, ::Int)` ends up calling `pow(::Float32, ::Float32)`
pow(x::Number, y::Number) = pow(promote(x, y)...)
pow(x::T, y::T) where {T<:Number} = pow(float(x), float(y))
pow(x::Real, y::Real) = pow(promote(x, y)...)
pow(x::T, y::T) where {T<:Real} = pow(float(x), float(y))

Check warning on line 37 in src/NaNMath.jl

View check run for this annotation

Codecov / codecov/patch

src/NaNMath.jl#L37

Added line #L37 was not covered by tests
pow(x, y) = ^(x, y)

# The following combinations are safe, so we can fall back to ^
pow(x::Number, y::Integer) = x^y
pow(x::Real, y::Integer) = x^y
pow(x::Complex, y::Complex) = x^y

"""
Expand Down
15 changes: 15 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,18 @@ using Test
@test isnan(NaNMath.max(NaN, NaN))
@test isnan(NaNMath.max(NaN))
@test NaNMath.max(NaN, NaN, 0.0, 1.0) == 1.0

# Test forwarding
x = 1 + 2im
for f in (:sin, :cos, :tan, :asin, :acos, :acosh, :atanh, :log, :log2, :log10,
:log1p, :sqrt)
@test @eval (NaNMath.$f)(x) == $f(x)
end

struct A end
Base.isless(::A, ::A) = false
y = A()
for f in (:max, :min)
@test @eval (NaNMath.$f)(y, y) == $f(y, y)
end
@test NaNMath.pow(x, x) == ^(x, x)
Loading