I am getting wrong answer for factorial(22)

조회 수: 3 (최근 30일)
Liam Sullivan
Liam Sullivan 2020년 1월 15일
댓글: Steven Lord 2020년 1월 15일
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