Internal Rate of Return - Code

Hi, I'm trying to write a iteration- loop to calculate te internal rate of reuturn (IRR) (without the financial toolbox).
Problems are: how to set the while loop
how to set the iteration steps
solution so far: IRR= -Inf -> why -Inf ?
My code so far:
zaeler=1; %% counter
w(1)=10;
w(2)=0;
IRR=0.05;
IRR1=0.1;
IRR2=0.2;
while zaeler<10000 %% better would be: while interval by 0
for jahr=1:1:25
s(jahr) = (cashflow(jahr)/((1+IRR)^jahr));
end
w(zaeler) = sum(s)-invest ; %% w should be 0
if w(zaeler)>0
IRR=IRR1-(w(1)/(w(2)-w(1)))*(IRR2-IRR1);
IRR1=IRR;
elseif w(zaeler)<0
IRR=IRR1-(w(1)/(w(2)-w(1)))*(IRR2-IRR1);
IRR2=IRR;
end
zaeler=zaeler+1;
end
Thank you in advance for your ideas and help.

댓글 수: 3

Rik
Rik 2021년 5월 11일
Did you step through your code with the debugger to see when the IRR becomes -inf?
Since you know the number of iterations: why aren't you using a for-loop instead?
Are you sure w will never be 0? Because neither branch will execute in that case, leaving IRR the same for the remaining iterations. Don't you want to put a break statement there?
MK
MK 2021년 5월 11일
Thank you for the hint with break!
I improved my code this way:
iteration=1;
w(1)=10; %start value
w(2)=0;
IRR=0.05;
IRR1=0.01; %Min IRR (start-value)
IRR2=0.5; %Max IRR
limit= 0.00001;
for iteration<10000
for jahr=1:1:25
s(jahr) = (cashflow(jahr)/((1+IRR)^jahr));
end
w(iteration) = sum(s)-invest ; % SOLL w= 0
if w(iteration)>= 0 && w(iteration)< limit
break
elseif w(iteration)> limit %% IRR to hight
IRR= (IRR1+IRR2)/2;
IRR1=IRR; %% set IRR lower
elseif w(iteration)<0 %% IRR to low -> (w<0)
IRR= (IRR1+IRR2)/2
IRR2=IRR; %% IRR higher
end
% IRR_check(iteration)=IRR ;
iteration=iteration+1;
end
I get these values for w: (to high values and converge to a value far from 0)
there must be a mistake in setting the IRR, I guess.
w: 1x9999 double =
1.0e+05 *
Columns 1 through 12
-3.1570 -5.4823 -4.9124 -3.8592 -2.7531 -1.9262 -1.4160 -1.1320 -0.9821 -0.9051 -0.8660 -0.8463
Columns 13 through 24
-0.8365 -0.8315 -0.8291 -0.8278 -0.8272 -0.8269 -0.8267 -0.8267 -0.8266 -0.8266 -0.8266 -0.8266
Columns 25 through 36
-0.8266 -0.8266 -0.8266 -0.8266 -0.8266 -0.8266 -0.8266 -0.8266 -0.8266 -0.8266 -0.8266 -0.8266
...
Rik
Rik 2021년 5월 11일
You should step through your code and closely look at what values your variables have after each line.
And why did you write for iteration<10000? It does something, but I expect you want for iteration=1:10000 instead (and remove iteration=iteration+1;).

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

답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

MK
2021년 5월 11일

댓글:

Rik
2021년 5월 11일

Community Treasure Hunt

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

Start Hunting!

Translated by