FixedPoint

Struct FixedPoint 

Source
pub struct FixedPoint {
    pub value: U256,
}
Expand description

A fixed-point number with 18 decimal places of precision.

This type represents decimal numbers using integer arithmetic, scaled by 10^18. All arithmetic operations maintain the scale factor automatically.

§Examples

// Create 5.5
let x = FixedPoint::from_fraction(5, 1, 2)?; // 5 + 1/2
 
// Create from float (testing only)
let y = FixedPoint::from_f64(2.5)?;

// Arithmetic
let sum = x.add(&y)?; // 8.0

Fields§

§value: U256

The raw U256 value, scaled by 10^18

Implementations§

Source§

impl FixedPoint

Source

pub fn from_int(n: u64) -> Self

Creates a fixed-point number from an unsigned 64-bit integer.

The integer is automatically scaled by 10^18 to maintain precision.

§Arguments
  • n - The integer value to convert
§Examples
let five = FixedPoint::from_int(5);
assert_eq!(five.to_u64()?, 5);
Source

pub fn from_u128(n: u128) -> Self

Creates a fixed-point number from an unsigned 128-bit integer.

Similar to from_int, but accepts larger values.

§Arguments
  • n - The 128-bit integer value to convert
§Examples
let large = FixedPoint::from_u128(1_000_000_000);
Source

pub fn from_scaled(value: U256) -> Self

Creates a fixed-point number from a raw scaled U256 value.

This function assumes the input is already scaled by 10^18. Use this when you have a pre-scaled value.

§Arguments
  • value - The pre-scaled U256 value
§Safety

The caller must ensure the value is properly scaled.

Source

pub fn from_scaled_u128(value: u128) -> Self

Creates a fixed-point number from a raw scaled u128 value.

This function assumes the input is already scaled by 10^18.

§Arguments
  • value - The pre-scaled u128 value
Source

pub fn to_u64(&self) -> Result<u64>

Converts the fixed-point number to a u64 integer.

This operation truncates any decimal places. For example, 5.7 becomes 5, and 5.3 becomes 5.

§Returns

The integer part as u64, or an error if the value is too large.

§Errors
  • MathError::Overflow - If the value exceeds u64::MAX
§Examples
let x = FixedPoint::from_fraction(5, 7, 10)?; // 5.7
assert_eq!(x.to_u64()?, 5);
Source

pub fn to_u128(&self) -> Result<u128>

Converts the fixed-point number to a u128 integer.

Truncates any decimal places, similar to to_u64 but with larger range.

§Returns

The integer part as u128, or an error if the value is too large.

§Errors
  • MathError::Overflow - If the value exceeds u128::MAX
Source

pub fn to_f64(&self) -> Result<f64>

Converts the fixed-point number to an f64 float.

This is primarily intended for debugging and testing purposes. Precision may be lost for very large or very precise numbers.

§Returns

The floating-point representation, or an error if overflow occurs.

§Errors
  • MathError::Overflow - If the value is too large for f64 conversion
§Examples
let x = FixedPoint::from_int(5);
assert!((x.to_f64()? - 5.0).abs() < 1e-10);
Source

pub fn from_f64(val: f64) -> Result<Self>

Creates a fixed-point number from an f64 float.

This is intended for testing and convenience. For production code, prefer using integer-based constructors for deterministic behavior.

§Arguments
  • val - The floating-point value (must be non-negative and finite)
§Returns

A new FixedPoint, or an error if the input is invalid.

§Errors
  • MathError::InvalidInput - If val is negative, infinite, or NaN
  • MathError::Overflow - If val is too large to represent
§Examples
let x = FixedPoint::from_f64(3.14159)?;
Source

pub fn from_fraction( whole: u64, numerator: u64, denominator: u64, ) -> Result<Self>

Creates a fixed-point number from fractional components.

Computes: whole + (numerator / denominator)

§Arguments
  • whole - The integer part
  • numerator - Numerator of the fractional part
  • denominator - Denominator of the fractional part (must be non-zero)
§Returns

The resulting fixed-point number.

§Errors
  • MathError::DivisionByZero - If denominator is zero
§Examples
// Create 5.5 (5 + 1/2)
let x = FixedPoint::from_fraction(5, 1, 2)?;
Source

pub fn from_ratio(numerator: u64, denominator: u64) -> Result<Self>

Creates a fixed-point number from a simple ratio.

Computes: numerator / denominator

§Arguments
  • numerator - The numerator
  • denominator - The denominator (must be non-zero)
§Examples
// Create 0.5 (1/2)
let half = FixedPoint::from_ratio(1, 2)?;
Source

pub fn from_bps(bps: u64) -> Result<Self>

Creates a fixed-point number from basis points.

Basis points are 1/100th of a percent. 1 bp = 0.01% = 0.0001

§Arguments
  • bps - The number of basis points
§Examples
// 250 bps = 2.5%
let rate = FixedPoint::from_bps(250)?;
Source

pub fn from_percent(percent: u64) -> Result<Self>

Creates a fixed-point number from a percentage.

§Arguments
  • percent - The percentage value (e.g., 25 for 25%)
§Examples
// 25% = 0.25
let quarter = FixedPoint::from_percent(25)?;
Source

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

Multiplies two fixed-point numbers.

§Arguments
  • other - The number to multiply by
§Returns

The product of the two numbers.

§Errors
  • MathError::Overflow - If the result exceeds U256::MAX
§Examples
let x = FixedPoint::from_int(5);
let y = FixedPoint::from_int(3);
let product = x.mul(&y)?; // 15
Source

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

Divides one fixed-point number by another.

§Arguments
  • other - The divisor (must be non-zero)
§Returns

The quotient.

§Errors
  • MathError::DivisionByZero - If other is zero
  • MathError::Overflow - If the result exceeds U256::MAX
§Examples
let x = FixedPoint::from_int(10);
let y = FixedPoint::from_int(4);
let quotient = x.div(&y)?; // 2.5
Source

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

Adds two fixed-point numbers.

§Arguments
  • other - The number to add
§Returns

The sum of the two numbers.

§Errors
  • MathError::Overflow - If the sum exceeds U256::MAX
Source

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

Subtracts one fixed-point number from another.

§Arguments
  • other - The number to subtract
§Returns

The difference.

§Errors
  • MathError::Underflow - If other is larger than self
Source

pub fn pow2_fast(exponent: &Self) -> Result<Self>

Optimized power function for base 2 with fractional exponents.

Computes 2^exponent using range reduction and Taylor series. This is more efficient than the general power function.

§Arguments
  • exponent - The exponent (can be fractional)
§Returns

2 raised to the given power.

§Errors
  • MathError::Overflow - If the result is too large
§Examples
let exp = FixedPoint::from_int(3);
let result = FixedPoint::pow2_fast(&exp)?; // 2^3 = 8
Source

pub fn pow(&self, exponent: &Self) -> Result<Self>

Raises this number to the given power.

Supports both integer and fractional exponents. Uses optimized algorithms based on the base and exponent values.

§Arguments
  • exponent - The power to raise to (can be fractional)
§Returns

self^exponent

§Errors
  • MathError::InvalidInput - If self is zero and exponent is non-positive
  • MathError::Overflow - If the result is too large
§Examples
let base = FixedPoint::from_int(5);
let exp = FixedPoint::from_int(2);
let result = base.pow(&exp)?; // 25

// Fractional exponent (square root)
let half = FixedPoint::from_ratio(1, 2)?;
let sqrt_25 = FixedPoint::from_int(25).pow(&half)?; // 5
Source

pub fn ln(&self) -> Result<Self>

Computes the natural logarithm (ln).

§Returns

ln(self)

§Errors
  • MathError::InvalidInput - If self is zero or negative
§Examples
let e = FixedPoint::from_f64(2.718281828)?;
let ln_e = e.ln()?; // ≈ 1.0
Source

pub fn exp(&self) -> Result<Self>

Computes the exponential function (e^x).

§Returns

e^self

§Errors
  • MathError::Overflow - If self is too large
§Examples
let x = FixedPoint::from_int(1);
let e = x.exp()?; // ≈ 2.718281828
Source

pub fn sqrt(&self) -> Result<Self>

Computes the square root using Newton’s method.

§Returns

√self

§Examples
let x = FixedPoint::from_int(25);
let sqrt = x.sqrt()?; // 5
Source

pub fn log10(&self) -> Result<Self>

Computes the base-10 logarithm.

Uses the identity: log10(x) = ln(x) / ln(10)

§Returns

log₁₀(self)

§Errors
  • MathError::InvalidInput - If self is zero
Source

pub fn log2(&self) -> Result<Self>

Computes the base-2 logarithm.

Uses the identity: log2(x) = ln(x) / ln(2)

§Returns

log₂(self)

§Errors
  • MathError::InvalidInput - If self is zero
Source

pub fn log(&self, base: &Self) -> Result<Self>

Computes the logarithm with a custom base.

Uses the identity: log_base(x) = ln(x) / ln(base)

§Arguments
  • base - The logarithm base
§Returns

log_base(self)

§Errors
  • MathError::InvalidInput - If self or base is zero or base is 1
Source

pub fn abs(&self) -> Self

Returns the absolute value.

For unsigned fixed-point numbers, this is always the identity function.

§Examples
let x = FixedPoint::from_int(5);
assert_eq!(x.abs(), x);
Source

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

Returns the minimum of two values.

§Arguments
  • other - The value to compare with
§Examples
let x = FixedPoint::from_int(5);
let y = FixedPoint::from_int(3);
assert_eq!(x.min(&y), y);
Source

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

Returns the maximum of two values.

§Arguments
  • other - The value to compare with
§Examples
let x = FixedPoint::from_int(5);
let y = FixedPoint::from_int(3);
assert_eq!(x.max(&y), x);
Source

pub fn is_zero(&self) -> bool

Checks if this value is zero.

§Returns

true if the value is exactly zero, false otherwise

Source

pub fn debug_value(&self) -> (u64, u64, u64, u64)

Returns the raw internal U256 representation for debugging.

The U256 is stored as 4 u64 limbs.

§Returns

A tuple of (limb0, limb1, limb2, limb3)

Source

pub fn frac(&self) -> Result<Self>

Returns the fractional part of this number.

For example, the fractional part of 5.7 is 0.7.

§Examples
let x = FixedPoint::from_fraction(5, 7, 10)?; // 5.7
let frac = x.frac()?;
// frac ≈ 0.7
Source

pub fn floor(&self) -> Self

Returns the integer part (floor) of this number.

§Examples
let x = FixedPoint::from_fraction(5, 7, 10)?; // 5.7
let floor = x.floor();
assert_eq!(floor.to_u64()?, 5);
Source

pub fn ceil(&self) -> Result<Self>

Returns the ceiling of this number.

Rounds up to the next integer if there’s any fractional part.

§Examples
let x = FixedPoint::from_fraction(5, 7, 10)?; // 5.7
let ceil = x.ceil()?;
assert_eq!(ceil.to_u64()?, 6);

Trait Implementations§

Source§

impl Clone for FixedPoint

Source§

fn clone(&self) -> FixedPoint

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 Debug for FixedPoint

Source§

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

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

impl PartialEq for FixedPoint

Source§

fn eq(&self, other: &FixedPoint) -> 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 Copy for FixedPoint

Source§

impl Eq for FixedPoint

Source§

impl StructuralPartialEq for FixedPoint

Auto Trait Implementations§

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> Same for T

Source§

type Output = T

Should always be Self
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.