Expand description
Arbitrary-precision rational number arithmetic using crypto-bigint integers.
This library provides Ratio<T>, a generic rational number type supporting
any crypto-bigint unsigned integer from U64 to U16384.
§Features
- Generic over integer width: Works with U256, U512, U1024, U2048, etc.
- Performance-focused: Deferred reduction and smart heuristics
- Overflow handling: Automatic fallback to wider types when needed
- no_std compatible: Works in embedded and constrained environments
§Design Philosophy
Operations like multiplication and addition return unreduced results by default.
Call Ratio::normalize explicitly when reduction is needed. This design
improves performance in loops and chained operations.
For convenience, Ratio::mul_reduced provides smart reduction using fast
heuristics that avoid expensive GCD operations when possible.
§Examples
§Basic Usage
use crypto_ratio::Ratio;
use crypto_bigint::U256;
// Create rationals
let a = Ratio::<U256>::from_u64(1, 2); // 1/2
let b = Ratio::<U256>::from_u64(1, 3); // 1/3
// Operations return unreduced results
let sum = &a + &b; // 5/6
assert_eq!(sum.numer, U256::from_u64(5));
assert_eq!(sum.denom, U256::from_u64(6));
// Explicit reduction when needed
let product = &a * &b; // 1/6 (unreduced as 2/12)
let mut reduced = product.clone();
reduced.normalize();
assert_eq!(reduced.numer, U256::from_u64(1));
assert_eq!(reduced.denom, U256::from_u64(6));§Type Aliases
use crypto_ratio::RatioU512;
let r = RatioU512::from_u64(3, 4);
assert_eq!(r.to_f64_approx(), 0.75);§Deferred Reduction Pattern
use crypto_ratio::RatioU512;
// Accumulate without reduction
let mut sum = RatioU512::zero();
let increment = RatioU512::from_u64(1, 100);
for _ in 0..10 {
sum = sum.add(&increment);
}
// Reduce once at the end
sum.normalize();Re-exports§
pub use crate::ratio_trait::RatioInteger;pub use crate::ratio_trait::WideInteger;
Modules§
- ratio_
trait - Trait system for generic rational number arithmetic over crypto-bigint types.
Structs§
- Ratio
- A rational number represented as numerator/denominator with explicit sign.
Type Aliases§
- Ratio
U64 - Ratio using 64-bit integers.
- Ratio
U128 - Ratio using 128-bit integers.
- Ratio
U256 - Ratio using 256-bit integers.
- Ratio
U512 - Ratio using 512-bit integers (recommended for most use cases).
- Ratio
U1024 - Ratio using 1024-bit integers.
- Ratio
U2048 - Ratio using 2048-bit integers.
- Ratio
U4096 - Ratio using 4096-bit integers.
- Ratio
U8192 - Ratio using 8192-bit integers.
- Ratio
U16384 - Ratio using 16384-bit integers.