why do i get this nan

UL=100;
LL=0;
n=LL:1:UL;
E1 = 2.^(n+1);
E2 = (gamma(n+1)).^2;
E3 = gamma(2.*n+2);
E = (E1.*E2./E3);
S2 = (sum(E)).^-1

Risposte (2)

Alan Stevens
Alan Stevens il 28 Ago 2020

1 voto

UL is generating numbers too large for E3. Try reducing UL to 90.
John D'Errico
John D'Errico il 28 Ago 2020
Modificato: John D'Errico il 28 Ago 2020
Time to learn to use logs. Yes, I know you probably know what a log is. But you appear not to know why you need to use them here.
The gamma function acts like factorial. It grows REALLY fast. That means it easily overflows the dynamic rangoe of a double. And remember this identity:
factorial(n) = gamma(n+1)
when n is an integer. So the gamma function gets BIG.
What happens when you do things like this?
inf/inf
ans =
NaN
YOU GET A NAN! You can multiply infs and still get inf. But inf/inf is indeterminate, since you don't know exactly how "big" each of those infs really was. So you get a NaN. A few other operations also produce a NaN, all of which are indeterminate. For example, inf-inf, 0/0, 0*inf, sin(inf), etc. In your case, the problem was probably inf/inf.
But what are you doing with it? You are multiplying and dividing by big numbers. USE LOGS. And now you can take advantage of the gammaln function. Do some reading:
help gammaln
Now to fix your code.
UL=100;
LL=0;
n=LL:1:UL;
E1 = log(2)*(n+1);
E2 = (gammaln(n+1))*2;
E3 = gammaln(2.*n+2);
There will now be no overflows. Since we are working in logs...
E = E1 + E2 - E3;
Finally, all we need to do is exponentiate. Everything was a natural log. When we exponentiate, will there be any problems?
min(E)
ans =
-71.0486757527832
max(E)
ans =
0.693147180559945
Nope. Everything will stay nicely in the dynamic range of a double.
E = exp(E);
S2 = 1/sum(E) % be serious. All you wanted to do was to take the reciprocal of the sum
S2 =
-0.000275777075563896
No problems now. USE LOGS FOR THESE PROBLEMS.

Categorie

Scopri di più su Elementary Math in Centro assistenza e File Exchange

Tag

Richiesto:

il 28 Ago 2020

Commentato:

il 29 Ago 2020

Community Treasure Hunt

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

Start Hunting!

Translated by