Why can't Matlab do the factorial of a non-integer number?

조회 수: 23 (최근 30일)
HWIK
HWIK 2022년 2월 6일
댓글: Dyuman Joshi 2024년 1월 23일
Hi,
I tried using the factorial function on a number with decimals and got the following error: N must be an array of real non-negative integers.
Is there an alternative so that it can calculate the factorial of a number with decimals like Excel does?
Thanks for your time

채택된 답변

Davide Masiello
Davide Masiello 2022년 2월 6일
편집: Davide Masiello 2022년 2월 6일
MatLab 'factorial' is coded so to work with integers only.
The generalization of a factorial is the Γ function, which is
and the relation with the factorial is
MatLab implements the Γ function. Therefore, to compute the factorial of 1.5 you can write
gamma(2.5)
Which yields 1.3293, the correct answer.
  댓글 수: 2
Andy
Andy 2024년 1월 23일
편집: Andy 2024년 1월 23일
Would you know how to calculate the inverse gamma function in Matlab?
f(1.3293) = 2.5.
I tried gaminv(1.3293) but it doesn't seem related. Same with gammaincinv.
I'm trying to find a real number whose factorial is equal to a number that I input.
Dyuman Joshi
Dyuman Joshi 2024년 1월 23일
There is no function in MATLAB, in-built or a part of the toolbox, that offers that functionality directly.
(Possibly because) There is no known explicit relation or definition which can be utilized to obtain that.
However, you can try this -
%value of which the inverse is to be calculated
y = gamma(2.5)
y = 1.3293
f = @(x, val) gamma(x) - val;
out = fzero(@(x) f(x, y), 2)
out = 2.5000
But note that the inverse gamma function is not one-on-one (reference - Graph of the function provided in its wikipedia article - https://en.wikipedia.org/wiki/Inverse_gamma_function), so multiple solutions exist for each input.
The value obtained as the output depends on the initial guess -
%Finding the inverse for the same, but with initial guess as 1
fzero(@(x) f(x, y), 1)
ans = 0.6809

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

추가 답변 (2개)

David Hill
David Hill 2022년 2월 6일
Use the gamma function.
gamma(1.3);

DGM
DGM 2022년 2월 6일
See the Gamma function
Or in MATLAB, gamma().
Note that if you're trying to replicate the behavior of factorial, the input is offset by 1:
factorial([2 3 4])
ans = 1×3
2 6 24
gamma([2 2.5 3 3.2 3.6 4])
ans = 1×6
1.0000 1.3293 2.0000 2.4240 3.7170 6.0000
gamma([2 2.5 3 3.2 3.6 4]+1) % offset by 1
ans = 1×6
2.0000 3.3234 6.0000 7.7567 13.3813 24.0000

카테고리

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

태그

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by