memory overflow with double factorial function
Ältere Kommentare anzeigen
I am trying to create a recursive formula to calculate the double factorial of a number, n. The code I have come up with currently is as follows:
function [DFact] = DFactorialRec(n)
DFact = n*DFactorialRec(n-2)
end
This clearly does not work as it will recursively continue for negative values of n. Please could someone suggest an alteration to stop the memory overflow error?
================================================================
Out of memory. The likely cause is an infinite recursion within the program.
Error in DFactorialRec (line 2)
DFact = n*DFactorialRec(n-2)
================================================================
Thanks!
5 Kommentare
David Goodmanson
am 9 Okt. 2020
Bearbeitet: David Goodmanson
am 9 Okt. 2020
Hi Harry,
this is one of the the standard issues with recursion: when to stop. You just need to insert an if statement so that if n = 1 (having started with odd n originally) or n = 0 (having started with even n originally) then the output of DFactorialRec equals 1, and otherwise you do the recursive call that you already have.
Harry Rogers
am 9 Okt. 2020
Walter Roberson
am 9 Okt. 2020
function [DFact] = DFactorialRec(n)
if n==0
disp("n is equal to 1")
DFact = 1;
else if n==1
disp("n is equal to 1")
DFact = 1;
else
DFact = n*DFactorialRec(n-2);
end
end
end
However I would recommend you rewrite using elseif instead of else if
Harry Rogers
am 9 Okt. 2020
Walter Roberson
am 9 Okt. 2020
The code I posted worked for me provided that n is a scalar. If it is a non-scalar then you have the problem that your if is comparing a non-scalar to a scalar, and that comparison might be true for some elements but false for others...
Akzeptierte Antwort
Weitere Antworten (1)
SteveC
am 22 Jul. 2024
Bearbeitet: Walter Roberson
am 22 Jul. 2024
The double factorial of an integer -1 and larger is defined as in
and generalized in the Pochhammer symbol
It appears in electromagnetic expansions and in special functions.
if the argument is an integer -1 and larger, it is written in Matlab as
fDF = @(bb) prod(bb:(-1):1)
For a vector example
>> arrayfun(fDF,-1:5)
1 1 1 2 6 24 120
If the application manages the validity of the argument, a single line without parity check is OK to define the function.
For big args, a Stirling form...
1 Kommentar
Kategorien
Mehr zu Scripts finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!