Why can't Matlab do the factorial of a non-integer number?
14 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
HWIK
am 6 Feb. 2022
Kommentiert: Dyuman Joshi
am 23 Jan. 2024
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
0 Kommentare
Akzeptierte Antwort
Davide Masiello
am 6 Feb. 2022
Bearbeitet: Davide Masiello
am 6 Feb. 2022
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 Kommentare
Dyuman Joshi
am 23 Jan. 2024
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)
f = @(x, val) gamma(x) - val;
out = fzero(@(x) f(x, y), 2)
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)
Weitere Antworten (2)
DGM
am 6 Feb. 2022
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])
gamma([2 2.5 3 3.2 3.6 4])
gamma([2 2.5 3 3.2 3.6 4]+1) % offset by 1
0 Kommentare
Siehe auch
Kategorien
Mehr zu Special Functions finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!