citronrose
citronrose

Reputation: 409

Minimizing rounding errors in square root of fraction

In R I have

options(digits=22)
sqrt((1-exp(-20)))/sqrt((1-exp(-19.9)))
> 1.000000000108386855047
sqrt((1-exp(-20))/(1-exp(-19.9)))
> 1.000000000108386633002

My question is: can I expect one version to be more precise than the other, (also in other languages), or is it dependent on the implementation of division and sqrt?

Upvotes: 0

Views: 84

Answers (1)

gammatester
gammatester

Reputation: 1141

This is because your second expression is wrong. It should be sqrt((1-exp(-10))/(1-exp(-9))), you computed the square root of a value like 1-a/(1-b) instead of (1-a)/(1-b).

With this change both results are 1.000039008990497.


Here is the updated answer: Computing sqrt(1-x) is a bit more inaccurate for small x. To get a slightly better result you can approximate with a Taylor series sqrt(1-x) ~ 1 - x/2 (or higher terms, dependent on the value of x).

> x = exp(-20)
> y = exp(-19.9)
> sqrt((1-x)/(1-y))
[1] 1.0000000001083866
> sqrt(1-x)/sqrt(1-y)
[1] 1.0000000001083869
> (1-x/2)/(1-y/2)
[1] 1.0000000001083866

The correct rounded value is 1.0000000001083867. You can see that the Taylor series value is the same as the first. IMO the differences are very small and normally not worth using the Taylor series.

Upvotes: 1

Related Questions