why do i get this nan

2 ビュー (過去 30 日間)
bahar çakmak
bahar çakmak 2020 年 8 月 28 日
コメント済み: bahar çakmak 2020 年 8 月 29 日
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

回答 (2 件)

Alan Stevens
Alan Stevens 2020 年 8 月 28 日
UL is generating numbers too large for E3. Try reducing UL to 90.

John D'Errico
John D'Errico 2020 年 8 月 28 日
編集済み: John D'Errico 2020 年 8 月 28 日
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.
  1 件のコメント
bahar çakmak
bahar çakmak 2020 年 8 月 29 日
thank you so much for the detailed answer!

サインインしてコメントする。

カテゴリ

Help Center および File Exchange2-D and 3-D Plots についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by