use crate::ONE;
use rust_decimal::prelude::*;
pub fn cagr(beginning_balance: Decimal, ending_balance: Decimal, n: Decimal) -> Decimal {
(ending_balance / beginning_balance).powd(ONE / n) - ONE
}
#[cfg(test)]
mod tests {
#[cfg(not(feature = "std"))]
extern crate std;
use super::*;
use rust_decimal_macros::dec;
#[cfg(not(feature = "std"))]
use std::assert;
#[cfg(not(feature = "std"))]
use std::prelude::v1::*;
#[test]
fn test_cagr() {
let beginning_balance = dec!(1000);
let ending_balance = dec!(500);
let n = dec!(5);
let result = cagr(beginning_balance, ending_balance, n);
let expected = dec!(-0.12945);
assert!(
(result - expected).abs() < dec!(1e-5),
"Failed on case: {}. Expected: {}, Result: {}",
"Beginning balance of $1000, ending balance of $500 after 5 years",
expected,
result
);
}
}