How to make sure that ratios of very large numbers(e^​1000+1)/(e​^1000-1) is not given as NaN?

2 views (last 30 days)
I am trying to plot a function
T = (exp(x) + 1)/(exp(x) - 1)
where x ranges from say -10000 to 10000. Since exp(x) will be very large, the MATLAB is giving NaN instead of actual values. How to overcome this?
Thank you.

Accepted Answer

James Tursa
James Tursa on 20 Apr 2018
Edited: James Tursa on 20 Apr 2018

You can use an alternate formula for the large values:

T = (1 + 1./exp(x)) ./ (1 - 1./exp(x))

Note that once x gets large enough (19), the ratio calculation becomes equivalent to the "first order" approximation 1 + 2/exp(x) because of the limits of double precision arithmetic.

  3 Comments
James Tursa
James Tursa on 20 Apr 2018
Edited: James Tursa on 20 Apr 2018

A general answer is probably not possible. It will depend on the calculations being done. First one would look to see if the ratio has a finite limit. Simple inspection or algebraic manipulation of your particular example easily shows that it does. Then either look for a simple rearrangement of terms so that the numerator & denominator converge instead of diverge, or divide things out to reduce it to a series that converges rapidly enough to be of practical use. I did both above. E.g., just doing a long divide results in this:

T = 1 + 2/exp(x) + 2/exp(x)^2 + 2/exp(x)^3 + ...

Those 2/exp(x)^n terms are going to rapidly become insignificant compared to 1 for double precision arithmetic as x gets large. It only takes x=19 before the entire ratio calculation becomes equivalent to only the first term approximation of 1 + 2/exp(x), and when x=38 the 2/exp(x) part becomes smaller than eps(1) and no longer has any effect on the double precision result.

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 20 Apr 2018

If you use the symbolic toolbox, you could

syms x x0
T = (exp(x) + 1)/(exp(x) - 1);
Tt = taylor(T, x, x0, 'Order', 20)
Tt160 = simplify(subs(Tt, x0, 160));
fplot(Tt160, [120 200]);

and do other x0 values for higher accuracy in local ranges.

... Looks like Order 100 is pretty hard for MATLAB to process... I'm going to have to shoot that session it looks like!

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!