Ratio

Struct Ratio 

Source
pub struct Ratio<T: RatioInteger> {
    pub numer: T,
    pub denom: T,
    pub negative: bool,
}
Expand description

A rational number represented as numerator/denominator with explicit sign.

§Type Parameter

T must implement RatioInteger, which includes all crypto-bigint types from U64 through U16384.

§Invariants

  • Denominator is never zero
  • Values are not automatically reduced (call normalize explicitly)
  • Sign is stored separately in the negative field
  • Zero is always represented with negative = false

§Examples

use crypto_ratio::Ratio;
use crypto_bigint::U512;

let r = Ratio::<U512>::from_u64(2, 3);
assert_eq!(r.numer, U512::from_u64(2));
assert_eq!(r.denom, U512::from_u64(3));
assert!(!r.negative);

Fields§

§numer: T

The numerator.

§denom: T

The denominator.

§negative: bool

Sign of the rational (true = negative).

Implementations§

Source§

impl<T: RatioInteger> Ratio<T>

Source

pub fn new_raw(numer: T, denom: T, negative: bool) -> Self

Create a ratio without reduction.

The denominator must be non-zero. This method is fast but the caller is responsible for calling normalize if needed.

§Examples
use crypto_ratio::Ratio;
use crypto_bigint::U256;

let r = Ratio::new_raw(U256::from_u64(4), U256::from_u64(6), false);
assert_eq!(r.numer, U256::from_u64(4)); // Not reduced
assert_eq!(r.denom, U256::from_u64(6));
Source

pub fn new(numer: T, denom: T) -> Self

Create a ratio with automatic GCD reduction.

This is slower than new_raw but ensures the result is in lowest terms.

§Examples
use crypto_ratio::Ratio;
use crypto_bigint::U256;

let r = Ratio::new(U256::from_u64(4), U256::from_u64(6));
assert_eq!(r.numer, U256::from_u64(2)); // Reduced
assert_eq!(r.denom, U256::from_u64(3));
Source

pub fn from_u64(numer: u64, denom: u64) -> Self

Create from u64 with automatic reduction.

This is the most efficient constructor for small values.

§Examples
use crypto_ratio::RatioU256;

let r = RatioU256::from_u64(6, 8);
assert_eq!(r.to_f64_approx(), 0.75);
Source

pub fn one() -> Self

Create a ratio representing 1.

Source

pub fn zero() -> Self

Create a ratio representing 0.

Source

pub fn neg(self) -> Self

Negate the ratio, flipping its sign.

Source

pub fn abs(&self) -> Self

Get the absolute value.

Source

pub fn is_zero(&self) -> bool

Check if the ratio is zero.

Source

pub fn is_positive(&self) -> bool

Check if the ratio is positive.

Source

pub fn is_negative(&self) -> bool

Check if the ratio is negative.

Source

pub fn is_integer(&self) -> bool

Check if the ratio represents an integer (denominator is 1).

Source

pub fn needs_reduction(&self) -> bool

Check if the ratio should be reduced to prevent overflow.

Returns true if either numerator or denominator exceeds the reduction threshold (typically 70% of the type’s bit width).

Source

pub fn normalize_if_needed(&mut self)

Normalize only if needs_reduction returns true.

This is useful in loops to avoid unnecessary GCD operations.

Source

pub fn normalize(&mut self)

Reduce the ratio to lowest terms using GCD.

This operation is optimized to:

  • Return immediately if already reduced (GCD = 1)
  • Use bit shifts for power-of-2 factors
  • Normalize zero to 0/1
§Examples
use crypto_ratio::RatioU256;

let mut r = RatioU256::new_raw(
    crypto_bigint::U256::from_u64(6),
    crypto_bigint::U256::from_u64(8),
    false
);
r.normalize();
assert_eq!(r.numer, crypto_bigint::U256::from_u64(3));
assert_eq!(r.denom, crypto_bigint::U256::from_u64(4));
Source

pub fn from_float(f: f64) -> Option<Self>

Convert an f64 to a ratio with automatic reduction.

Returns None if the input is infinite or NaN.

§Examples
use crypto_ratio::RatioU512;

let r = RatioU512::from_float(0.75).unwrap();
assert_eq!(r.numer, crypto_bigint::U512::from_u64(3));
assert_eq!(r.denom, crypto_bigint::U512::from_u64(4));
Source

pub fn to_f64_approx(&self) -> f64

Approximate conversion to f64.

Large values are scaled to fit in f64 range, potentially losing precision.

§Examples
use crypto_ratio::RatioU256;

let r = RatioU256::from_u64(1, 2);
assert!((r.to_f64_approx() - 0.5).abs() < 1e-10);
Source

pub fn add(&self, other: &Self) -> Self

Add two ratios.

Returns an unreduced result. Call normalize if needed.

§Examples
use crypto_ratio::RatioU256;

let a = RatioU256::from_u64(1, 2);
let b = RatioU256::from_u64(1, 3);
let sum = a.add(&b);
// Result is 5/6
Source

pub fn mul(&self, other: &Self) -> Self

Multiply two ratios without automatic reduction.

For reduced results, use mul_reduced or call normalize afterward.

§Examples
use crypto_ratio::RatioU256;

let a = RatioU256::from_u64(2, 3);
let b = RatioU256::from_u64(3, 4);
let product = a.mul(&b);
// Result is 6/12 (unreduced)
Source

pub fn mul_reduced(&self, other: &Self) -> Self

Multiply with smart reduction using fast heuristics.

This applies cheap reduction techniques:

  • Power-of-2 factors via bit shifts (~10ns)
  • Small value GCD using u64 (~50ns)
  • Skips expensive full GCD for large coprime values
§Examples
use crypto_ratio::RatioU256;

let a = RatioU256::from_u64(2, 3);
let b = RatioU256::from_u64(3, 4);
let product = a.mul_reduced(&b);
// Result is 1/2 (reduced)
Source

pub fn div_by_uint(&self, divisor: &T) -> Self

Divide by an unsigned integer.

Multiplies the denominator by the divisor.

Source

pub fn sub(&self, other: &Self) -> Self

Subtract another ratio.

Equivalent to self.add(&other.neg()).

Source

pub fn div(&self, other: &Self) -> Self

Divide by another ratio.

§Panics

Panics if other is zero.

Source

pub fn recip(&self) -> Self

Get the reciprocal (1/x).

§Panics

Panics if the ratio is zero.

Source

pub fn lt(&self, other: &Self) -> bool

Less-than comparison optimized for both small and large values.

Uses fast paths for:

  • Sign differences
  • Large magnitude differences
  • Small values (≤64 bits)
Source

pub fn gt(&self, other: &Self) -> bool

Greater-than comparison optimized for both small and large values.

Uses fast paths for:

  • Sign differences
  • Large magnitude differences
  • Small values (≤64 bits)

Trait Implementations§

Source§

impl<T: RatioInteger> Add for &Ratio<T>

Source§

type Output = Ratio<T>

The resulting type after applying the + operator.
Source§

fn add(self, other: Self) -> Ratio<T>

Performs the + operation. Read more
Source§

impl<T: RatioInteger> Add for Ratio<T>

Source§

type Output = Ratio<T>

The resulting type after applying the + operator.
Source§

fn add(self, other: Self) -> Self

Performs the + operation. Read more
Source§

impl<T: Clone + RatioInteger> Clone for Ratio<T>

Source§

fn clone(&self) -> Ratio<T>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Debug + RatioInteger> Debug for Ratio<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: RatioInteger> Div for &Ratio<T>

Source§

type Output = Ratio<T>

The resulting type after applying the / operator.
Source§

fn div(self, other: Self) -> Ratio<T>

Performs the / operation. Read more
Source§

impl<T: RatioInteger> Div for Ratio<T>

Source§

type Output = Ratio<T>

The resulting type after applying the / operator.
Source§

fn div(self, other: Self) -> Self

Performs the / operation. Read more
Source§

impl<T: RatioInteger> Mul for &Ratio<T>

Source§

type Output = Ratio<T>

The resulting type after applying the * operator.
Source§

fn mul(self, other: Self) -> Ratio<T>

Performs the * operation. Read more
Source§

impl<T: RatioInteger> Mul for Ratio<T>

Source§

type Output = Ratio<T>

The resulting type after applying the * operator.
Source§

fn mul(self, other: Self) -> Self

Performs the * operation. Read more
Source§

impl<T: RatioInteger> Neg for Ratio<T>

Source§

type Output = Ratio<T>

The resulting type after applying the - operator.
Source§

fn neg(self) -> Self

Performs the unary - operation. Read more
Source§

impl<T: RatioInteger> Ord for Ratio<T>

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<T: RatioInteger> PartialEq for Ratio<T>

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T: RatioInteger> PartialOrd for Ratio<T>

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<T: RatioInteger> Sub for &Ratio<T>

Source§

type Output = Ratio<T>

The resulting type after applying the - operator.
Source§

fn sub(self, other: Self) -> Ratio<T>

Performs the - operation. Read more
Source§

impl<T: RatioInteger> Sub for Ratio<T>

Source§

type Output = Ratio<T>

The resulting type after applying the - operator.
Source§

fn sub(self, other: Self) -> Self

Performs the - operation. Read more
Source§

impl<T: RatioInteger> Eq for Ratio<T>

Auto Trait Implementations§

§

impl<T> Freeze for Ratio<T>
where T: Freeze,

§

impl<T> RefUnwindSafe for Ratio<T>
where T: RefUnwindSafe,

§

impl<T> Send for Ratio<T>
where T: Send,

§

impl<T> Sync for Ratio<T>
where T: Sync,

§

impl<T> Unpin for Ratio<T>
where T: Unpin,

§

impl<T> UnwindSafe for Ratio<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.