How to avoid NaN due to rounding errors
Consider the calculation
x * -3/10 + sqrt(1/20 - x^2 / 100)
when x=sqrt(5)
. The sqrt argument becomes negative due to a rounding error, and the result of the entire expression NaN
.
> x <- sqrt(5)
> x * -3/10 + sqrt(1/20 - x^2 / 100)
[1] NaN
Warning message:
In sqrt(1/20 - sqrt(5)^2/100) : NaNs produced
Correct result
> sqrt(5) * -3/10
[1] -0.6708204
source to share
If you don't want square root to return values NaN
, one parameter should simply be used pmax
to make sure its argument is at least 0:
x * -3/10 + sqrt(pmax(0, 1/20 - x^2 / 100))
# [1] -0.6708204
If you want it to return NaN
when the argument is sqrt
fairly negative but 0 when it is actually close to 0 but negative, then it ifelse
might help:
x <- sqrt(4:6)
special.sqrt <- function(x) ifelse(x < -1e-10, NaN, sqrt(pmax(0, x)))
x * -3/10 + special.sqrt(1/20 - x^2 / 100)
# [1] -0.5000000 -0.6708204 NaN
source to share