Fraction
- Fraction data type with lossless arithmetic that is more precise than float and can be used for hashing.
- The main goal of Fraction is keeping precision that floats cannot do.
- Fractions do not lose information about numbers and thus can be used for matching, comparisons and hashing (key values for HashMaps).
- Base arithmetic operators are also available (+ - / *), even though they work slower than for native numbers.
- Overflow checks are being performed for every arithmetic operation, so that Fraction becomes infinite, negative_infinite or NaN.
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));
}
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 (3, 4))); assert! (map.contains_key (&Fraction::new (6, 8))); assert! (map.contains_key (&Fraction::new (12, 16))); assert! (! map.contains_key (&Fraction::from (0.5))); }
Comparison
use fraction::Fraction;
fn main () {
let f14 = Fraction::new (1, 4); let f12 = Fraction::new (1, 2); let f24 = Fraction::new (2, 4); let f34 = Fraction::new (3, 4);
assert_eq! (f12, f24); assert_eq! (f34, f12 + f14); assert_eq! (f14, Fraction::from (0.25)); }