I am getting wrong answer for factorial(22)

3 次查看(过去 30 天)
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

回答(1 个)

James Tursa
James Tursa 2020-1-15
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 个评论
Liam Sullivan
Liam Sullivan 2020-1-15
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 2020-1-15
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by