I don't know what you're trying to do but this problem has been described so many time on SO it's not funny anymore.
Let's paint a picture:
you start off with
dt = T / nsteps;
which is my first red flag.
then you do:
if t==T
where t = t + dt
Why is that wrong? Because of this wonderful thing called quantization. In other words there will be a time when because of super small micro difference, the result will not be correct. The bigger nsteps is, the worse this will be.
And then to add insult to injury, you put this line in
elseif t<T ... end
which means your code will skip everything, and you'll return nothing, causing your code to crash.
How does one solve this? If you can move integers around instead of floating values, you'll be in a better position. So instead of dt, you can have currentStep
, such that:
function [y]=AmericanPutClassic (St, currentStep)
if nargin < 2
currentStep = 0;
end
...
if currentStep>=nsteps % if t==T
...
else
...
upPrice=AmericanPutClassic(St*u,currentStep+1);
...
end