Skip to main content

f64_to_ratio_approx

Function f64_to_ratio_approx 

Source
pub fn f64_to_ratio_approx(x: f64, max_denom: u64) -> Option<Ratio<BigInt>>
Expand description

Best rational approximation to x with denominator at most max_denom.

Walks the continued-fraction convergents (and semiconvergents) of the exact value of x, so the result is the closest rational with a denominator not exceeding max_denom — this is what turns 0.1 into 1/10, 0.3333333333333333 into 1/3, and 3.14159 into 355/113 (for max_denom = 1000).

Returns None for NaN / ±∞ or max_denom == 0.

§Examples

use symplex::base::numeric::f64_to_ratio_approx;
use num_bigint::BigInt;
use num_rational::Ratio;

let r = |p: i64, q: i64| Ratio::new(BigInt::from(p), BigInt::from(q));
assert_eq!(f64_to_ratio_approx(0.1, 1_000_000), Some(r(1, 10)));
assert_eq!(f64_to_ratio_approx(1.0 / 3.0, 1_000_000), Some(r(1, 3)));
assert_eq!(f64_to_ratio_approx(0.3, 1_000_000), Some(r(3, 10)));
assert_eq!(f64_to_ratio_approx(std::f64::consts::PI, 1000), Some(r(355, 113)));
assert_eq!(f64_to_ratio_approx(-2.5, 10), Some(r(-5, 2)));
assert_eq!(f64_to_ratio_approx(7.0, 1), Some(r(7, 1)));