Factorial using a for loop

조회 수: 21 (최근 30일)
Joseph
Joseph 2023년 4월 14일
댓글: John D'Errico 2023년 4월 14일
I need to write a for loop that calculates the factorial 100
This is the code that I have written. I now need to display the value of 100! and asign it to the variable nf
How could I go about that?
n=100
x=1
for b=1:n
x=x*b
end

답변 (2개)

Walter Roberson
Walter Roberson 2023년 4월 14일
편집: Walter Roberson 2023년 4월 14일
n=75;
x=sym(1);
for b=1:n
x=x*b;
end
nf_sym = x
nf_sym = 
24809140811395398091946477116594033660926243886570122837795894512655842677572867409443815424000000000000000000
You will not be able to calculate this accurately using double precision.
format long g
n=75;
x=(1);
for b=1:n
x=x*b;
end
nf = x
nf =
2.48091408113954e+109
double(nf_sym) - nf
ans =
8.34369935906606e+93
That is, the final digits in the pure double precision calculation are not correct compared to calculating exactly and taking double precision afterwards.

Les Beckham
Les Beckham 2023년 4월 14일
Your code works fine (though I would add semicolons to the end of all lines except the for and end to avoid spewing a bunch of stuff to the command window).
Then add this after your existing code to "assign it to the variable nf". Or, you could just replace the x variable with nf.
nf = x
  댓글 수: 2
Les Beckham
Les Beckham 2023년 4월 14일
Also, if you are just getting started with Matlab, I would highly recommend that you take a couple of hours to go through the free online tutorial: Matlab Onramp
John D'Errico
John D'Errico 2023년 4월 14일
All correct. I would add however, that factorial(100) is NOT representable exactly as a double precision number.
factorial(100)
ans = 9.3326e+157
So only the first 16 decimal digits of that result will be correct.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Special Functions에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by