0.1.0 |
|
---|
#23 in #naive
25KB
543 lines
Ben's Naive Rational Numbers Crate | Last Updated 2/3/2021
This crate serves as a basic implementation of a fraction. It aims to behave exactly how you expect it to, and leave as many decisions about the structure as possible up to you.
+, +=, -, -=, *, *=, /, /= are all overloaded and .abs() and .pow(u32) methods are provided. This data structure is exactly as likely to overflow as the datatype you base it on, so be careful with pow(). There is also a rat![] macro.
A rational number is defined as any number which can be represented as an integer divided by another (but non zero) integer. This crate is MUCH less strict than that. All that is required to create a "rational number", which is actually just a fraction, is that your type T implement the following traits: Add<Output = T> + Mul<Output = T> + Sub<Output = T> + Rem<Output = T> + Div<Output = T> + PartialEq + PartialOrd + Copy
That being said, please do not try to make a rational number out of floats, it will break everything, because many of the algorithms involved in manipulation of the fraction require exact values (think gcd).
This crate is designed to be used with primative data types for exact math operations. In the future I hope to make it more robust so that it stands up to your custom data types.
Examples
use bens_fractions::{Rational,rat};
assert_eq!(rat![8i64, 32i64], Rational::from(8i64, 32i64).unwrap());