I am getting wrong answer for factorial(22)

3 visualizzazioni (ultimi 30 giorni)
Liam Sullivan
Liam Sullivan il 15 Gen 2020
Commentato: Steven Lord il 15 Gen 2020
I keep getting 1.1198e+21 for factorial(22) but in the xample problem on matlab the answer is 1.24000728E21.
Problem
a1 = factorial(22)
b = (sqrt(2*pi*22))*(22^22/exp(22))
c = (abs((a1 - b)/a1))*100
Outputs
a1 = 1.1198e+21
b = 1.1198e+21
c = 0

Risposte (1)

James Tursa
James Tursa il 15 Gen 2020
R2016a PCWIN64:
>> a1 = factorial(22)
a1 =
1.124000727777608e+21
>> b = (sqrt(2*pi*22))*(22^22/exp(22))
b =
1.119751494628234e+21
>> c = (abs((a1 - b)/a1))*100
c =
0.378045409078625
What version of MATLAB are you running? Are you shadowing the MATLAB factorial( ) function with one of your own? I.e., what does this reply:
which factorial
  2 Commenti
Liam Sullivan
Liam Sullivan il 15 Gen 2020
Oh now it's giving me the correct answer. I am not sure what was wrong with it so i exited it out, reopened it and then ran the script again. Thanks though!
Steven Lord
Steven Lord il 15 Gen 2020
If the problem recurs, run the last line of code in James Tursa's answer and check that you're calling the factorial function included in MATLAB. Actually, I'd suggest a slight modification to James's code:
which -all factorial
The factorial.m in the toolbox\matlab\specfun directory is the factorial function included in MATLAB so it's OK. Any factorial.m files listed in the output of the above command whose entry ends with "<some class name> method" are OK as well. If you see other factorial.m files you may want to rename or remove them.

Accedi per commentare.

Categorie

Scopri di più su Programming in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by