pub fn fraction_to_percent(fraction: f64) -> f64 {
fraction * 100.0
}
pub fn percent_to_fraction(percent: f64) -> f64 {
percent / 100.0
}
const RATE_MIN: f64 = -0.05;
const RATE_MAX: f64 = 0.50;
const GROWTH_MIN: f64 = -0.10;
pub fn check_rate(name: &str, fraction: f64) -> Result<f64, String> {
if fraction.is_nan() {
return Err(format!("{name} is NaN"));
}
let floor = if name == "gdp_growth" { GROWTH_MIN } else { RATE_MIN };
if !(floor..=RATE_MAX).contains(&fraction) {
let hint = if fraction > 1.0 && fraction <= 100.0 {
format!(
" - this looks like a percent value. Rates are FRACTIONAL \
here: pass {} for {}%.",
fraction / 100.0,
fraction
)
} else {
String::new()
};
return Err(format!(
"{name} = {fraction} is outside the plausible range \
[{floor}, {RATE_MAX}]{hint}"
));
}
Ok(fraction)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips_exactly_for_representable_values() {
for percent in [0.0, 2.5, 4.0, 25.0, 100.0] {
assert_eq!(fraction_to_percent(percent_to_fraction(percent)), percent);
}
}
#[test]
fn converts_in_the_direction_the_docs_claim() {
assert_eq!(fraction_to_percent(0.045), 4.5);
assert_eq!(percent_to_fraction(4.5), 0.045);
}
#[test]
fn catches_a_percent_value_passed_to_a_fractional_api() {
let err = check_rate("corporate_bond_yield", 4.5).unwrap_err();
assert!(err.contains("looks like a percent value"), "{err}");
assert!(err.contains("0.045"), "{err}");
}
#[test]
fn admits_every_policy_rate_that_has_actually_happened() {
for (name, rate) in [
("ECB deposit rate, 2019", -0.005),
("Bank of Japan, 2016", -0.001),
("ZIRP", 0.0),
("US, 2023", 0.0533),
("Volcker peak, 1981", 0.20),
("emerging-market tightening", 0.45),
] {
assert!(check_rate("fed_funds", rate).is_ok(), "{name} ({rate}) rejected");
}
}
#[test]
fn rejects_beyond_the_band_at_both_ends() {
assert!(check_rate("fed_funds", -0.20).is_err());
assert!(check_rate("fed_funds", 0.75).is_err());
}
#[test]
fn rejects_nan_rather_than_simulating_it() {
assert!(check_rate("fed_funds", f64::NAN).is_err());
}
#[test]
fn a_bare_zero_is_legal() {
assert!(check_rate("fed_funds", 0.0).is_ok());
assert_eq!(fraction_to_percent(0.0), 0.0);
}
}