Skip to content

Instantly share code, notes, and snippets.

@musm
Created July 26, 2020 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save musm/1080639da2c5575cfe0fca39d77f70b6 to your computer and use it in GitHub Desktop.
Save musm/1080639da2c5575cfe0fca39d77f70b6 to your computer and use it in GitHub Desktop.
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))[])
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
# minimum times are exactly the same
@benchmark test1((Ref(2.2))[]);
@benchmark test2((Ref(2.2))[]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment