Article 6YS75 Numerical problem with an interest calculation

Numerical problem with an interest calculation

by
John
from John D. Cook on (#6YS75)

The previous post looked at the difference between continuously compounded interest and interest compounded a large discrete number of times. This difference was calculated using the following Python function.

 def f(P, n, r) : return P*(exp(r) - (1 + r/n)**n)

where the function arguments are principle, number of compoundings, and interest rate.

When I was playing around with this I noticed

 f(1000000, 365*24*60*60, 0.12)

returned a negative value, -0.00066. If this were correct, it would mean that compounding a 12% loan once a second results in more interest than continuous compounding. But this cannot happen. Compounding more often can only increase the amount of interest.

The problem with the Python function is that when n is very large, exp(r) and (1 + r/n)n are so nearly equal that their subtraction results in a complete loss of precision, a phenomenon known as catastrophic cancellation. The two terms are indistinguishable within the limits of floating point calculation because the former is the limit of the latter asn goes to infinity.

One way to calculate

exp(r) - (1 + r/n)n

for moderately small r (such as typical interest rates) and very large n (such as the number of seconds in a year) would be to write out the power series for exp(r), expand (1 + r/n)n using the binomial theorem, and subtract.

Then we find that

exp(r) - (1 + r/n)n r^2 / 2n

is a good approximation.

Whenn = 365 * 24 * 60 * 60 and r = 0.12, the approximation gives 2.28 * 10-10 and the correct result is 2.57 * 10-10. The approximation is only good to one significant figure, but it gets the sign and the order of magnitude correct. You could retain more series terms for more accuracy.

The post Numerical problem with an interest calculation first appeared on John D. Cook.
External Content
Source RSS or Atom Feed
Feed Location http://feeds.feedburner.com/TheEndeavour?format=xml
Feed Title John D. Cook
Feed Link https://www.johndcook.com/blog
Reply 0 comments