use num_bigint::BigInt;
use num_rational::Ratio;
use num_traits::{One, Signed, ToPrimitive, Zero};
pub type Frac = Ratio<BigInt>;
const MAX_CF_TERMS: usize = 200;
fn denom_limit() -> BigInt {
BigInt::from(10_u32).pow(18)
}
pub fn f64_to_fraction(x: f64) -> Option<Frac> {
if !x.is_finite() {
return None;
}
if x.fract() == 0.0 {
return integer_ratio(x);
}
let negative = x < 0.0;
let target = x.abs();
let mut rem = rational_of_f64(target);
let (mut h_prev, mut k_prev) = (BigInt::zero(), BigInt::one());
let (mut h_cur, mut k_cur) = (BigInt::one(), BigInt::zero());
for _ in 0..MAX_CF_TERMS {
let a = rem.to_integer();
let h = &a * &h_cur + &h_prev;
let k = &a * &k_cur + &k_prev;
h_prev = std::mem::replace(&mut h_cur, h);
k_prev = std::mem::replace(&mut k_cur, k);
if ratio_to_f64(&h_cur, &k_cur) == Some(target) {
let frac = Ratio::new(h_cur, k_cur);
return Some(if negative { -frac } else { frac });
}
rem -= Frac::from(a);
if rem.is_zero() {
break;
}
rem = rem.recip();
if k_cur > denom_limit() {
break;
}
}
decimal_fallback(x)
}
pub fn ratio_to_f64(h: &BigInt, k: &BigInt) -> Option<f64> {
use num_traits::Zero;
if k.is_zero() {
return None;
}
if h.is_zero() {
return Some(0.0);
}
let negative = h.is_negative();
let (h, k) = (h.magnitude(), k.magnitude()); let (bits_h, bits_k) = (h.bits() as i64, k.bits() as i64);
let mut s = 53 - (bits_h - bits_k);
let (mut t, mut twice_r) = scale_divide(h, k, s);
let tb = t.bits() as i64;
if tb < 53 {
s -= 53 - tb;
let (t2, r2) = scale_divide(h, k, s);
t = t2;
twice_r = r2;
} else if tb > 54 {
s += tb - 54;
let (t2, r2) = scale_divide(h, k, s);
t = t2;
twice_r = r2;
}
if &twice_r >= k {
t += 1u32;
}
let mantissa = t.to_f64()?; let value = mul_by_pow2(mantissa, -s); Some(if negative { -value } else { value })
}
fn mul_by_pow2(mut v: f64, mut e: i64) -> f64 {
while e > 512 {
v *= 2f64.powi(512);
e -= 512;
}
while e < -512 {
v *= 2f64.powi(-512);
e += 512;
}
v * 2f64.powi(e as i32)
}
fn scale_divide(
h: &num_bigint::BigUint,
k: &num_bigint::BigUint,
s: i64,
) -> (num_bigint::BigUint, num_bigint::BigUint) {
if s >= 0 {
let num = h << s as usize;
(&num / k, (&num % k) << 1)
} else {
let den = k << (-s) as usize;
(h / &den, (h % &den) << 1)
}
}
fn integer_ratio(n: f64) -> Option<Frac> {
let s = format!("{:.0}", n);
let big = BigInt::parse_bytes(s.as_bytes(), 10)?;
Some(Ratio::new(big, BigInt::one()))
}
fn rational_of_f64(x: f64) -> Frac {
debug_assert!(x.is_finite() && x > 0.0);
let bits = x.to_bits();
let raw_exp = ((bits >> 52) & 0x7ff) as i64;
let mantissa_field = bits & 0xf_ffff_ffff_ffff; let (m, e) = if raw_exp == 0 {
(mantissa_field, -1074_i64)
} else {
(mantissa_field | (1_u64 << 52), raw_exp - 1075)
};
let num = BigInt::from(m);
if e >= 0 {
Ratio::new(num << e as usize, BigInt::one())
} else {
Ratio::new(num, BigInt::one() << (-e) as usize)
}
}
fn decimal_fallback(x: f64) -> Option<Frac> {
let s = format!("{:.16e}", x.abs()); let (mant, exp) = s.split_once('e')?;
let digits: String = mant.chars().filter(|c| c.is_ascii_digit()).collect();
let exp: i64 = exp.parse().ok()?;
let num = BigInt::parse_bytes(digits.as_bytes(), 10)?;
let frac = if exp >= 16 {
Ratio::new(
num * BigInt::from(10_u32).pow((exp - 16) as u32),
BigInt::one(),
)
} else {
Ratio::new(num, BigInt::from(10_u32).pow((16 - exp) as u32))
};
if ratio_to_f64(frac.numer(), frac.denom()) == Some(x) {
Some(frac)
} else {
let exact = rational_of_f64(x.abs());
Some(if x < 0.0 { -exact } else { exact })
}
}
pub fn lift(n: f64) -> Option<Frac> {
f64_to_fraction(n)
}
#[cfg(test)]
mod tests {
use super::*;
fn frac(num: i64, den: i64) -> Frac {
Ratio::new(BigInt::from(num), BigInt::from(den))
}
#[test]
fn integer_fast_path() {
assert_eq!(f64_to_fraction(2.5e3), Some(frac(2500, 1)));
assert_eq!(f64_to_fraction(0.0), Some(frac(0, 1)));
assert_eq!(
f64_to_fraction(1e19),
Some(Ratio::new(
BigInt::parse_bytes(b"10000000000000000000", 10).unwrap(),
BigInt::one()
))
);
}
#[test]
fn continued_fraction_recovers_intent() {
assert_eq!(f64_to_fraction(1.0_f64 / 3.0), Some(frac(1, 3)));
assert_eq!(f64_to_fraction(0.1), Some(frac(1, 10)));
assert_eq!(f64_to_fraction(1e-7), Some(frac(1, 10_000_000)));
assert_eq!(f64_to_fraction(2.5), Some(frac(5, 2)));
assert_eq!(f64_to_fraction(-0.25), Some(frac(-1, 4)));
}
#[test]
fn round_trip_always_exact() {
for x in [
1.0 / 3.0,
0.1,
2.5,
std::f64::consts::PI,
1e-7,
1e15,
999_999_999_999_999.0,
0.1 + 0.2,
123.456,
5e-324, ] {
let f = f64_to_fraction(x).expect("有限值必须可转换");
assert_eq!(ratio_to_f64(f.numer(), f.denom()), Some(x), "往返失配: {x}");
}
}
#[test]
fn ratio_to_f64_is_correctly_rounded() {
use std::str::FromStr;
for (h, k) in [(1i64, 3i64), (7, 11), (123456789, 987654321)] {
let ours = ratio_to_f64(&BigInt::from(h), &BigInt::from(k)).unwrap();
assert_eq!(ours, h as f64 / k as f64, "{h}/{k}");
}
let h = BigInt::from_str("123456789012345678901234567890").unwrap();
let k = BigInt::from_str("987654321098765432109876543210").unwrap();
let v = ratio_to_f64(&h, &k).unwrap();
assert!((v - 0.125).abs() < 1e-8, "大数比值应接近 0.125,实际 {v}");
let sub = Ratio::new(BigInt::from(3u32), BigInt::one() << 1074usize);
assert_eq!(
ratio_to_f64(sub.numer(), sub.denom()),
Some(3.0 * f64::from_bits(1)), "次正规数转换"
);
assert_eq!(ratio_to_f64(&BigInt::zero(), &BigInt::one()), Some(0.0));
assert_eq!(ratio_to_f64(&BigInt::one(), &BigInt::zero()), None);
}
#[test]
fn non_finite_is_none() {
assert_eq!(f64_to_fraction(f64::NAN), None);
assert_eq!(f64_to_fraction(f64::INFINITY), None);
}
}