Reputation: 1946
I can't figure out how to recursively calculate the rate of return on an investment, where the principal is unknown, and only the rates and the duration of the rates are known.
For example, if I had an investment for 2 years at 10% (or 0.1), the RoR would equal 0.21 (or 21%). This is calculated non-recursively as,
0.21 = 2 * 0.1 + (0.1 ^ 2)
// or
ror = duration * rate + (rate ^ duration)
Since I may not want to only know the final calculation, but the intermittent years of that investment, I must do this recursively (e.g. if the duration is 5 years, I want to know what the rate of return is after the first year, the second year and so on).
Since this is an algorithm, C# isn't required, but that is what I will be programming it in.
Upvotes: 1
Views: 892
Reputation: 27233
The easiest to calculate recursively is 1.0+RoR:
double calculateRateOfReturnPlus1(double rate, int periods) {
if (periods == 0)
return 1.0;
return (1.0 + rate) * calculateRateOfReturnPlus1(rate, periods - 1);
}
This returns 1.21 for rate=0.1, periods=2 and 1.331 for rate=0.1, periods=3. You can then subtract 1.0 to obtain pure RoR. Alternatively, you can compute RoR directly like this:
double calculateRateOfReturn(double rate, int periods) {
if (periods == 0)
return 0.0;
return (1.0 + rate) * (calculateRateOfReturn(rate, periods - 1) + 1.0) - 1.0;
}
Also, you can calculate RoR iteratively like this:
double calculateRateOfReturn(double rate, int periods) {
double RoR = 1.0;
for (int i = 0; i < periods; i++) {
RoR = RoR * (1.0 + rate);
}
return RoR - 1.0;
}
The last two functions return 0.21 for rate=0.1, periods=2 and 0.331 for rate=0.1, periods=3.
In practice one would simply rely on the Math.Pow()
function:
double calculateRateOfReturn(double rate, int periods) {
return Math.Pow(1.0+rate, periods) - 1.0;
}
Upvotes: 2
Reputation: 2868
A LINQ version:
double rate = 0.1;
int totalYears = 5;
var results = Enumerable.Range(1, totalYears).Select(i => new { Year = i, RoR = Math.Pow(1 + rate, i) - 1 });
This gives you the rate of return for every year within the period.
Upvotes: 1
Reputation: 10665
I've done similar "modelling" in a spreadsheet, and the easiest way to do this is to calculate the compound interest for every year, and then in another column calculate the difference between successive years.
If you still want to use recursionto calculate yearly (or any other period) you could input the result of the calculation (starting with 1) as the principal for the next period.
So period 0 "rate" would be 1, then period 1 would be 1.1, period 2 would be 1.21 etc.
Upvotes: -1