Fraction
Lossless float that may be used in matching, ordering and hashing
More documentation available on docs.rs.
- The main goal of Fraction is to keep precision that floats cannot do
- Fractions can be used for matching and comparisons and thus for hashing
- Base arithmetic implemented upon
num
crate (rational
module)
Fraction
struct implementation uses two u64
numbers and arithmetic on stack
BigFraction
struct implementation uses two limitless BigUint
numbers and arithmetic on heap
Examples
Simple arithmetic
use fraction::Fraction;
fn main () {
let mut fr = Fraction::zero ();
fr = fr + Fraction::from (2); fr = fr / Fraction::from (0.5);
assert_eq! (fr, Fraction::from (4));
assert_eq! (4.0f64, fr.to_f64 ());
}
Using as keys for a HashMap
use std::collections::HashMap;
use fraction::Fraction;
fn main () {
let f = Fraction::from (0.75);
let mut map: HashMap<Fraction, ()> = HashMap::new ();
map.insert (f, ());
assert! (map.contains_key (&Fraction::new (3u64, 4u64))); assert! (map.contains_key (&Fraction::new (6u64, 8u64))); assert! (map.contains_key (&Fraction::new (12u64, 16u64))); assert! (! map.contains_key (&Fraction::from (0.5))); }
Comparison
use fraction::Fraction;
fn main () {
let f14 = Fraction::new (1u64, 4u64); let f12 = Fraction::new (1u64, 2u64); let f24 = Fraction::new (2u64, 4u64); let f34 = Fraction::new (3u64, 4u64);
assert_eq! (f12, f24); assert_eq! (f34, f12 + f14); assert_eq! (f14, Fraction::from (0.25)); }
Change Log
Look into CHANGELOG.md for details