#numbers #real-number #precision #cases

reals

Computable and unified real numbers

4 releases (breaking)

0.4.0 Mar 23, 2025
0.3.0 Mar 9, 2025
0.2.0 Mar 5, 2025
0.1.0 Mar 4, 2025

#499 in Math

Download history 225/week @ 2025-03-02 136/week @ 2025-03-09 7/week @ 2025-03-16 107/week @ 2025-03-23

475 downloads per month
Used in ralc

MIT license

100KB
2K SLoC

This crates implements a unified real number type as described in Towards an API for the Real Numbers. We represent a real number as the product of a rational number and a computable number, with an additional property tag to enable some basic symbolic computation. Thanks to this design, we are able to:

  • represent rational numbers exactly
  • evaluate irrational numbers to an arbitrary precision
  • perform basic symbolic computation for the "easy" cases

The ComputableReal type is from the computable_real crate, and we re-export it here. Most of the implementation is translated from UnifiedReal.java in the Android ART repository.

Example

use reals::Real;

// We parse from strings to avoid floating point errors.
let n1: Real = "7.23".parse().unwrap();
let n2: Real = "4.13".parse().unwrap();
let res = n1 + n2;
// `digits_required` tells us that the number can be exactly represented
// with 2 digits after the decimal point.
assert_eq!(res.digits_required(), Some(2));
// `trucated` renders the number to two decimal places.
assert_eq!(res.truncated(2), "11.36");

let pi = Real::pi();
// Pi cannot be exactly represented, so `digits_required` returns `None`.
assert_eq!(pi.digits_required(), None);
// We can still render it to an arbitrary precision.
assert_eq!(pi.truncated(10), "3.1415926535");

// sqrt(42) is irrational and cannot be exactly represented.
let n3 = Real::from(42).sqrt().unwrap();
assert_eq!(n3.digits_required(), None);
assert_eq!(n3.truncated(10), "6.4807406984");

// However, we can represent sqrt(42)^2 exactly thanks to the property tag.
let n4 = &n3 * &n3;
assert_eq!(n4.digits_required(), Some(0));
assert_eq!(n4.truncated(0), "42");

Dependencies

~515KB
~10K SLoC