How to avoid going over Realmax in calculations
Show older comments
I'm writing a function that calculates the sum of a Taylor Series based on an x input. One of the sub calculations, x.^k where k is growing by one with each iteration of the series, is breaking the realmax with larger input numbers; however, the final calculation is less than the realmax. When Matlab tries to calculate this one part of the function it gets the 'Inf' value and then the final value results to 'Inf' even though it should be much smaller than the realmax. Is there a way around this?
Answers (2)
Star Strider
on 3 Feb 2016
Edited: Star Strider
on 3 Feb 2016
How much accuracy or significant figures do you need? You may find that truncating the series before it gets as far as testing the realmax limit gives you enough significant figures.
Another option, especially if you’re dividing it by another large number (for instance a factorial), is to stay in ‘log-space’, then take the anti-log:
term = exp(k*log(x)-log(factorial(k)))
James Tursa
on 3 Feb 2016
Edited: James Tursa
on 3 Feb 2016
0 votes
You might also try reordering the calculation of each term. E.g., take the exponential series:
e^x = 1 + x + x^2/2! + x^3/3! + x^4/4! + ...
Instead of calculating each term explicitly as x^k/k!, calculate it as x*(last_term/k) where k increases by 1 each iteration. Maybe you can do something like this for your particular series to keep the intermediate calculations from overflowing.
Categories
Find more on Numeric Types in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!