Created
April 14, 2023 06:44
-
-
Save pedrovasconcellos/e95352257c61523f314bd6852069f4ad to your computer and use it in GitHub Desktop.
Internal Rate of Return
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let initial_investment = -1000.0; | |
let cash_receipts = vec![250.0, 350.0, 450.0, 550.0]; | |
let cash_flows = vec![initial_investment, | |
cash_receipts[0], cash_receipts[1], cash_receipts[2], cash_receipts[3]]; | |
let rate = irr(&cash_flows); | |
println!("IRR: {:.2}%", rate * 100.0); | |
} | |
fn irr(cash_flows: &[f64]) -> f64 { | |
let tolerance = 0.00001; | |
let mut min_rate = -0.9999; | |
let mut max_rate = 1.0; | |
let mut guess = 0.0; | |
while max_rate - min_rate > tolerance { | |
let mut sum_pv = 0.0; | |
for (i, cash_flow) in cash_flows.iter().enumerate() { | |
let t = i as f64; | |
let pv = cash_flow / ((1.0_f64 + guess).powf(t + 1.0_f64)); | |
sum_pv += pv; | |
} | |
if sum_pv > 0.0 { | |
min_rate = guess; | |
} else { | |
max_rate = guess; | |
} | |
guess = (max_rate + min_rate) / 2.0; | |
} | |
guess | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment