Factorial using a for loop
24 views (last 30 days)
Show older comments
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
0 Comments
Answers (2)
Walter Roberson
on 14 Apr 2023
Edited: Walter Roberson
on 14 Apr 2023
n=75;
x=sym(1);
for b=1:n
x=x*b;
end
nf_sym = x
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
double(nf_sym) - nf
That is, the final digits in the pure double precision calculation are not correct compared to calculating exactly and taking double precision afterwards.
0 Comments
Les Beckham
on 14 Apr 2023
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 Comments
Les Beckham
on 14 Apr 2023
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
on 14 Apr 2023
All correct. I would add however, that factorial(100) is NOT representable exactly as a double precision number.
factorial(100)
So only the first 16 decimal digits of that result will be correct.
See Also
Categories
Find more on Special Functions in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!