pub struct Rational { /* private fields */ }Expand description
A normalized exact rational number.
Implementations§
Source§impl Rational
impl Rational
Sourcepub const fn from_integer(value: i128) -> Self
pub const fn from_integer(value: i128) -> Self
Returns the exact integer value / 1.
Sourcepub fn try_new(
numerator: i128,
denominator: i128,
) -> Result<Self, RationalError>
pub fn try_new( numerator: i128, denominator: i128, ) -> Result<Self, RationalError>
Creates a normalized rational number from a numerator and denominator.
§Errors
Returns RationalError::ZeroDenominator when denominator == 0, and
returns overflow-related errors when canonical sign normalization cannot
be represented in the current integer type.
§Examples
use use_rational::{Rational, RationalError};
let rational = Rational::try_new(2, 4)?;
assert_eq!(rational, Rational::try_new(1, 2)?);
assert!(matches!(
Rational::try_new(1, 0),
Err(RationalError::ZeroDenominator)
));Sourcepub const fn denominator(&self) -> i128
pub const fn denominator(&self) -> i128
Returns the normalized positive denominator.
Sourcepub const fn is_integer(&self) -> bool
pub const fn is_integer(&self) -> bool
Returns true when the rational is an integer.
Sourcepub const fn to_integer(self) -> Option<i128>
pub const fn to_integer(self) -> Option<i128>
Returns the exact integer value when the rational is integral.
Sourcepub fn reciprocal(self) -> Result<Self, RationalError>
pub fn reciprocal(self) -> Result<Self, RationalError>
Returns the reciprocal when the rational is non-zero.
§Errors
Returns RationalError::DivisionByZero when self == 0.
Sourcepub fn checked_add(self, other: Self) -> Result<Self, RationalError>
pub fn checked_add(self, other: Self) -> Result<Self, RationalError>
Adds two rational numbers exactly.
§Errors
Returns RationalError::ArithmeticOverflow when the intermediate or
normalized result cannot be represented exactly.
Sourcepub fn checked_sub(self, other: Self) -> Result<Self, RationalError>
pub fn checked_sub(self, other: Self) -> Result<Self, RationalError>
Subtracts two rational numbers exactly.
§Errors
Returns RationalError::ArithmeticOverflow when the intermediate or
normalized result cannot be represented exactly.
Sourcepub fn checked_mul(self, other: Self) -> Result<Self, RationalError>
pub fn checked_mul(self, other: Self) -> Result<Self, RationalError>
Multiplies two rational numbers exactly.
§Errors
Returns RationalError::ArithmeticOverflow when the intermediate or
normalized result cannot be represented exactly.
Sourcepub fn checked_div(self, other: Self) -> Result<Self, RationalError>
pub fn checked_div(self, other: Self) -> Result<Self, RationalError>
Divides two rational numbers exactly.
§Errors
Returns RationalError::DivisionByZero when other == 0, and returns
RationalError::ArithmeticOverflow when the exact result cannot be
represented.