memory overflow with double factorial function
Show older comments
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 Comments
David Goodmanson
on 9 Oct 2020
Edited: David Goodmanson
on 9 Oct 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
on 9 Oct 2020
Walter Roberson
on 9 Oct 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
on 9 Oct 2020
Walter Roberson
on 9 Oct 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...
Accepted Answer
More Answers (1)
SteveC
on 22 Jul 2024
Edited: Walter Roberson
on 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 Comment
Categories
Find more on Scripts in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!