Created
July 26, 2020 19:09
-
-
Save musm/df55a5b693bde00e9c1ea2213a1b8611 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Base.Math: rem_pio2_kernel, sin_kernel, cos_kernel | |
function nansin(x::T) where T<:Union{Float64} | |
absx = abs(x) | |
if absx < T(pi)/4 #|x| ~<= pi/4, no need for reduction | |
if absx < sqrt(eps(T)) | |
return x | |
end | |
return sin_kernel(x) | |
elseif isnan(x) | |
return T(NaN) | |
elseif isinf(x) | |
return T(NaN) | |
end | |
n, y = rem_pio2_kernel(x) | |
n = n&3 | |
if n == 0 | |
return sin_kernel(y) | |
elseif n == 1 | |
return cos_kernel(y) | |
elseif n == 2 | |
return -sin_kernel(y) | |
else | |
return -cos_kernel(y) | |
end | |
end | |
using StaticArrays, BenchmarkTools | |
x = 2.3 | |
# minimum times are exactly the same | |
@benchmark sin($(Ref(x))[]) | |
@benchmark nansin($(Ref(x))[]) | |
let v = @SVector(rand(20)), x = 5.0 | |
sinx = Base.sin(x) | |
@btime $v .+ $sinx | |
@btime $v .+ sin($x) | |
end | |
const v = @SVector(rand(20)) | |
function test1(x) | |
sinx = nansin(x) | |
return v .+ sinx | |
end | |
function test2(x) | |
sinx = sin(x) | |
return v .+ sinx | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment