#interval #unit #numbers #fraction #arithmetic-operations

no-std unit-interval

Types for working with and constraining values to the unit interval

1 unstable release

0.1.0 Aug 23, 2024

#746 in Math

MIT license

27KB
454 lines

Unit Interval

Crates.io Documentation

A small crate that provide type-level constrain for numerical values.

Features

  • Type level representation of values in [0, 1]
  • Checked and clamped arithmetic operations
  • Conversion to and from the underlying numeric type
  • Error types for values outside the interval
  • Support for various numeric types through generics

Documentation

For examples and information about the API, please check the documentation.

Motivation

This crate came about as an over-engineered way to work with fractions at a type-level for a ratio type.


lib.rs:

A small crate for working with numbers in the unit interval.

This crate currently only provides the UnitInterval type, which represents a number constrained to the closed interval between 0 and 1, inclusive. It offers operations, bounds checking, and utilities for working with values in this range.

Quick Start

To get started, create a UnitInterval using one of the many constructor methods:

use unit_interval::UnitInterval;

// Create a UnitInterval, panics if out of bounds
let a = UnitInterval::new(0.5);

// Create a UnitInterval, returns a Result
let b = UnitInterval::new_checked(0.75).unwrap();

// Create a UnitInterval, clamping the value to [0, 1]
let c = UnitInterval::new_clamped(1.5);
assert_eq!(c.into_inner(), 1.0);

Perform operations on UnitInterval values:

use unit_interval::UnitInterval;

let a = UnitInterval::new(0.3);
let b = UnitInterval::new(0.5);

// Multiplication always stays within [0, 1]
let product = a * b;
assert_eq!(product.into_inner(), 0.15);

// Other operations may need checking or clamping
let sum = a.checked_add(b).unwrap();
let difference = a.clamped_sub(b);

Dependencies

~150KB