1use num_bigint::BigInt;
16use num_rational::Ratio;
17use num_traits::{One, Signed, ToPrimitive, Zero};
18
19pub type Frac = Ratio<BigInt>;
21
22const MAX_CF_TERMS: usize = 200;
25
26fn denom_limit() -> BigInt {
28 BigInt::from(10_u32).pow(18)
29}
30
31pub fn f64_to_fraction(x: f64) -> Option<Frac> {
43 if !x.is_finite() {
44 return None;
45 }
46 if x.fract() == 0.0 {
48 return integer_ratio(x);
49 }
50 let negative = x < 0.0;
52 let target = x.abs();
53 let mut rem = rational_of_f64(target);
54
55 let (mut h_prev, mut k_prev) = (BigInt::zero(), BigInt::one());
57 let (mut h_cur, mut k_cur) = (BigInt::one(), BigInt::zero());
58
59 for _ in 0..MAX_CF_TERMS {
60 let a = rem.to_integer();
61 let h = &a * &h_cur + &h_prev;
62 let k = &a * &k_cur + &k_prev;
63 h_prev = std::mem::replace(&mut h_cur, h);
64 k_prev = std::mem::replace(&mut k_cur, k);
65
66 if ratio_to_f64(&h_cur, &k_cur) == Some(target) {
68 let frac = Ratio::new(h_cur, k_cur);
69 return Some(if negative { -frac } else { frac });
70 }
71
72 rem -= Frac::from(a);
73 if rem.is_zero() {
74 break;
76 }
77 rem = rem.recip();
78 if k_cur > denom_limit() {
79 break;
80 }
81 }
82 decimal_fallback(x)
83}
84
85pub fn ratio_to_f64(h: &BigInt, k: &BigInt) -> Option<f64> {
93 use num_traits::Zero;
94 if k.is_zero() {
95 return None;
96 }
97 if h.is_zero() {
98 return Some(0.0);
99 }
100 let negative = h.is_negative();
101 let (h, k) = (h.magnitude(), k.magnitude()); let (bits_h, bits_k) = (h.bits() as i64, k.bits() as i64);
103
104 let mut s = 53 - (bits_h - bits_k);
106 let (mut t, mut twice_r) = scale_divide(h, k, s);
107 let tb = t.bits() as i64;
109 if tb < 53 {
110 s -= 53 - tb;
111 let (t2, r2) = scale_divide(h, k, s);
112 t = t2;
113 twice_r = r2;
114 } else if tb > 54 {
115 s += tb - 54;
116 let (t2, r2) = scale_divide(h, k, s);
117 t = t2;
118 twice_r = r2;
119 }
120
121 if &twice_r >= k {
123 t += 1u32;
124 }
125 let mantissa = t.to_f64()?; let value = mul_by_pow2(mantissa, -s); Some(if negative { -value } else { value })
128}
129
130fn mul_by_pow2(mut v: f64, mut e: i64) -> f64 {
133 while e > 512 {
135 v *= 2f64.powi(512);
136 e -= 512;
137 }
138 while e < -512 {
139 v *= 2f64.powi(-512);
140 e += 512;
141 }
142 v * 2f64.powi(e as i32)
143}
144
145fn scale_divide(
147 h: &num_bigint::BigUint,
148 k: &num_bigint::BigUint,
149 s: i64,
150) -> (num_bigint::BigUint, num_bigint::BigUint) {
151 if s >= 0 {
152 let num = h << s as usize;
153 (&num / k, (&num % k) << 1)
154 } else {
155 let den = k << (-s) as usize;
156 (h / &den, (h % &den) << 1)
157 }
158}
159
160fn integer_ratio(n: f64) -> Option<Frac> {
162 let s = format!("{:.0}", n);
163 let big = BigInt::parse_bytes(s.as_bytes(), 10)?;
164 Some(Ratio::new(big, BigInt::one()))
165}
166
167fn rational_of_f64(x: f64) -> Frac {
169 debug_assert!(x.is_finite() && x > 0.0);
170 let bits = x.to_bits();
171 let raw_exp = ((bits >> 52) & 0x7ff) as i64;
172 let mantissa_field = bits & 0xf_ffff_ffff_ffff; let (m, e) = if raw_exp == 0 {
174 (mantissa_field, -1074_i64)
176 } else {
177 (mantissa_field | (1_u64 << 52), raw_exp - 1075)
178 };
179 let num = BigInt::from(m);
180 if e >= 0 {
181 Ratio::new(num << e as usize, BigInt::one())
182 } else {
183 Ratio::new(num, BigInt::one() << (-e) as usize)
184 }
185}
186
187fn decimal_fallback(x: f64) -> Option<Frac> {
189 let s = format!("{:.16e}", x.abs()); let (mant, exp) = s.split_once('e')?;
191 let digits: String = mant.chars().filter(|c| c.is_ascii_digit()).collect();
192 let exp: i64 = exp.parse().ok()?;
193 let num = BigInt::parse_bytes(digits.as_bytes(), 10)?;
195 let frac = if exp >= 16 {
196 Ratio::new(
197 num * BigInt::from(10_u32).pow((exp - 16) as u32),
198 BigInt::one(),
199 )
200 } else {
201 Ratio::new(num, BigInt::from(10_u32).pow((16 - exp) as u32))
202 };
203 if ratio_to_f64(frac.numer(), frac.denom()) == Some(x) {
204 Some(frac)
205 } else {
206 let exact = rational_of_f64(x.abs());
208 Some(if x < 0.0 { -exact } else { exact })
209 }
210}
211
212pub fn lift(n: f64) -> Option<Frac> {
218 f64_to_fraction(n)
219}
220
221#[cfg(test)]
222mod tests {
223 use super::*;
224
225 fn frac(num: i64, den: i64) -> Frac {
226 Ratio::new(BigInt::from(num), BigInt::from(den))
227 }
228
229 #[test]
230 fn integer_fast_path() {
231 assert_eq!(f64_to_fraction(2.5e3), Some(frac(2500, 1)));
232 assert_eq!(f64_to_fraction(0.0), Some(frac(0, 1)));
233 assert_eq!(
235 f64_to_fraction(1e19),
236 Some(Ratio::new(
237 BigInt::parse_bytes(b"10000000000000000000", 10).unwrap(),
238 BigInt::one()
239 ))
240 );
241 }
242
243 #[test]
244 fn continued_fraction_recovers_intent() {
245 assert_eq!(f64_to_fraction(1.0_f64 / 3.0), Some(frac(1, 3)));
247 assert_eq!(f64_to_fraction(0.1), Some(frac(1, 10)));
248 assert_eq!(f64_to_fraction(1e-7), Some(frac(1, 10_000_000)));
249 assert_eq!(f64_to_fraction(2.5), Some(frac(5, 2)));
250 assert_eq!(f64_to_fraction(-0.25), Some(frac(-1, 4)));
251 }
252
253 #[test]
254 fn round_trip_always_exact() {
255 for x in [
256 1.0 / 3.0,
257 0.1,
258 2.5,
259 std::f64::consts::PI,
260 1e-7,
261 1e15,
262 999_999_999_999_999.0,
263 0.1 + 0.2,
264 123.456,
265 5e-324, ] {
267 let f = f64_to_fraction(x).expect("有限值必须可转换");
268 assert_eq!(ratio_to_f64(f.numer(), f.denom()), Some(x), "往返失配: {x}");
269 }
270 }
271
272 #[test]
273 fn ratio_to_f64_is_correctly_rounded() {
274 use std::str::FromStr;
275 for (h, k) in [(1i64, 3i64), (7, 11), (123456789, 987654321)] {
277 let ours = ratio_to_f64(&BigInt::from(h), &BigInt::from(k)).unwrap();
278 assert_eq!(ours, h as f64 / k as f64, "{h}/{k}");
279 }
280 let h = BigInt::from_str("123456789012345678901234567890").unwrap();
282 let k = BigInt::from_str("987654321098765432109876543210").unwrap();
283 let v = ratio_to_f64(&h, &k).unwrap();
284 assert!((v - 0.125).abs() < 1e-8, "大数比值应接近 0.125,实际 {v}");
285 let sub = Ratio::new(BigInt::from(3u32), BigInt::one() << 1074usize);
287 assert_eq!(
288 ratio_to_f64(sub.numer(), sub.denom()),
289 Some(3.0 * f64::from_bits(1)), "次正规数转换"
291 );
292 assert_eq!(ratio_to_f64(&BigInt::zero(), &BigInt::one()), Some(0.0));
294 assert_eq!(ratio_to_f64(&BigInt::one(), &BigInt::zero()), None);
295 }
296
297 #[test]
298 fn non_finite_is_none() {
299 assert_eq!(f64_to_fraction(f64::NAN), None);
300 assert_eq!(f64_to_fraction(f64::INFINITY), None);
301 }
302}