Getting NaN greater values in a function

11 ビュー (過去 30 日間)
Yousaf Farrukh
Yousaf Farrukh 2022 年 10 月 7 日
コメント済み: Yousaf Farrukh 2022 年 10 月 7 日
Hey there, I am trying to plot a function, that works perfect for smaller values but as I input the larger values I get NaN as output. Below is the code for what coded:
clearvars;
iterations = [10, 100, 1000];
count = 1;
p = 0.5;
for n = iterations
figure();
hold on;
for k = 1:n
binomial = (factorial(n)) / (factorial(k) * factorial(n - k)) * (p^k * (1-p)^(n-k));
plot(k, binomial, '*');
end
end
As shown in the above graphs, I get the output for the iterations 10 &100, but there is no output for for 1000. Even if I replace 10 by 1000 I get the same output so I am sure its nothing related to the indexing.

採用された回答

Torsten
Torsten 2022 年 10 月 7 日
編集済み: Torsten 2022 年 10 月 7 日
warning('off')
iterations = [10, 100, 1000];
count = 1;
p = 0.5;
for n = iterations
figure();
hold on;
for k = 1:n
%binomial = nchoosek(n,k) * p^k * (1-p)^(n-k);
binomial = exp(sum(log(n-(0:k-1)))-sum(log(1:k))) * p^k * (1-p)^(n-k);
plot(k, binomial, '*');
end
end
  2 件のコメント
Yousaf Farrukh
Yousaf Farrukh 2022 年 10 月 7 日
It works!! Thanks. Can you help me understand why is it different from what I wrote? I believe nchoosek function is same as so why does it give NaN?
Stephen23
Stephen23 2022 年 10 月 7 日
編集済み: Stephen23 2022 年 10 月 7 日
"I believe nchoosek function is same as ... so why does it give NaN?"
Because calculating using factorials will very quickly get values well beyond those which can be represented using binary floating point numbers. Which is why NCHOOSEK uses another algorithm (hint: TYPE).

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

その他の回答 (1 件)

Steven Lord
Steven Lord 2022 年 10 月 7 日
What is the factorial of 1000 in double precision?
factorial(1000)
ans = Inf
It overflows. If we computed it symbolically, using arbitrary precision arithmetic:
vpa(factorial(sym(1000)))
ans = 
4.02387260077093773543702433923e+2567
That's a lot larger than realmax so it is not surprising it overflows.
realmax
ans = 1.7977e+308
Most likely you're dividing Inf by either Inf (if the denominator overflows), NaN, or 0 (if the denominator underflows.)
Inf ./ [Inf, NaN, 0]
ans = 1×3
NaN NaN Inf
The plot function doesn't display NaN values.
If you use nchoosek as @Torsten suggested it avoids computing such large numbers and then dividing a large numerator by a large denominator.
  1 件のコメント
Yousaf Farrukh
Yousaf Farrukh 2022 年 10 月 7 日
Got it thank you!!

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

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by