Added Quantity type

This commit is contained in:
2023-04-01 13:50:52 -07:00
parent 1181c5322f
commit a38f68cd84
8 changed files with 716 additions and 56 deletions

7
src/quantity/mod.rs Normal file
View File

@ -0,0 +1,7 @@
mod rationalq;
pub mod quantity;
pub use crate::quantity::quantity::Quantity;
const FLOAT_PRECISION: u32 = 2048;
const PRINT_LEN: usize = 4; // How many significant digits we will show in output

336
src/quantity/quantity.rs Normal file
View File

@ -0,0 +1,336 @@
use rug::Float;
use rug::ops::Pow;
use std::ops::{
Add, Sub, Mul, Div,
Neg, Rem,
AddAssign, SubAssign,
MulAssign, DivAssign
};
use std::cmp::Ordering;
use crate::quantity::rationalq::RationalQ;
use crate::quantity::FLOAT_PRECISION;
use crate::quantity::PRINT_LEN;
#[derive(Debug)]
#[derive(Clone)]
pub enum Quantity {
Rational{ v: RationalQ },
Float{ v: Float }
}
impl ToString for Quantity{
fn to_string(&self) -> String {
let (sign, mut string, exp) = match self {
Quantity::Float { v } => { v.to_sign_string_exp(10, Some(PRINT_LEN)) }
Quantity::Rational { v } => { v.to_sign_string_exp(10, Some(PRINT_LEN)) }
};
// zero, nan, or inf.
let sign = if sign {"-"} else {""};
if exp.is_none() { return format!("{sign}{string}"); }
let exp = exp.unwrap();
// Remove trailing zeros.
// At this point, string is guaranteed to be nonzero.
while string.chars().last().unwrap() == '0' {
string.remove(string.len() - 1);
}
let exp_u: usize;
if exp < 0 {
exp_u = (-exp).try_into().unwrap()
} else {
exp_u = exp.try_into().unwrap()
}
if exp_u >= 4 {
// Exponential notation
let pre = &string[0..1];
let post = &string[1..];
format!(
"{pre}{}{post}e{}{exp}",
if post.len() != 0 {"."} else {""},
if exp > 0 {"+"} else {""},
)
} else {
if exp <= 0 { // Decimal, needs `0.` and leading zeros
format!(
"0.{}{string}",
"0".repeat(exp_u)
)
} else if exp_u < string.len() { // Decimal, needs only `.`
format!(
"{}.{}",
&string[0..exp_u],
&string[exp_u..]
)
} else { // Integer, needs trailing zeros
format!(
"{string}{}",
"0".repeat(exp_u - string.len())
)
}
}
}
}
macro_rules! quick_quant_fn {
( $x:ident ) => {
pub fn $x(&self) -> Quantity {
match self {
Quantity::Float { v } => {Quantity::Float{ v:v.clone().$x()}},
Quantity::Rational { v } => {v.$x()}
}
}
}
}
impl Quantity {
pub fn new_float(f: f64) -> Quantity {
return Quantity::Float {
v: Float::with_val(FLOAT_PRECISION, f)
}
}
pub fn float_from_string(s: &str) -> Quantity {
let v = Float::parse(s);
return Quantity::Float {
v: Float::with_val(FLOAT_PRECISION, v.unwrap())
}
}
pub fn new_rational(top: i64, bottom: i64) -> Quantity {
return Quantity::Rational {
v: RationalQ::new(top, bottom)
}
}
pub fn new_rational_from_f64(f: f64) ->
Option<Quantity> {
let r = RationalQ::from_f64(f);
if r.is_some() {
return Some(Quantity::Rational {
v: r.unwrap()
});
} else {
return None;
}
}
pub fn to_float(&self) -> Float {
match self {
Quantity::Float { v } => {v.clone()},
Quantity::Rational { v } => {v.to_float()}
}
}
quick_quant_fn!(fract);
quick_quant_fn!(abs);
quick_quant_fn!(floor);
quick_quant_fn!(ceil);
quick_quant_fn!(round);
quick_quant_fn!(sin);
quick_quant_fn!(cos);
quick_quant_fn!(tan);
quick_quant_fn!(asin);
quick_quant_fn!(acos);
quick_quant_fn!(atan);
quick_quant_fn!(sinh);
quick_quant_fn!(cosh);
quick_quant_fn!(tanh);
quick_quant_fn!(asinh);
quick_quant_fn!(acosh);
quick_quant_fn!(atanh);
quick_quant_fn!(ln);
quick_quant_fn!(log10);
quick_quant_fn!(log2);
pub fn log(&self, base: Quantity) -> Quantity {
match (&self, &base) {
(Quantity::Float{v:a}, Quantity::Float{v:b}) => {Quantity::Float{v: a.clone().log10() / b.clone().log10()}},
(Quantity::Float{v:a}, Quantity::Rational{v:b}) => {Quantity::Float{v: a.clone().log10() / b.to_float().log10()}},
(Quantity::Rational{v:a}, _) => {a.log(base)}
}
}
pub fn is_zero(&self) -> bool {
match self {
Quantity::Float { v } => {v.is_zero()},
Quantity::Rational { v } => {v.is_zero()}
}
}
pub fn pow(&self, exp: Quantity) -> Quantity {
match self {
Quantity::Float { v } => {Quantity::Float {v: v.pow(exp.to_float())}},
Quantity::Rational { v } => {v.pow(exp) }
}
}
pub fn is_nan(&self) -> bool {
match self {
Quantity::Float { v } => {v.is_nan()},
Quantity::Rational { .. } => {panic!()}
}
}
}
impl Neg for Quantity where {
type Output = Self;
fn neg(self) -> Self::Output {
match self {
Quantity::Float { v } => {Quantity::Float{ v: -v }},
Quantity::Rational { v } => {Quantity::Rational { v: -v }},
}
}
}
impl Add for Quantity {
type Output = Self;
fn add(self, other: Self) -> Self::Output {
match (self, other) {
(Quantity::Float{v:a}, Quantity::Float{v:b}) => {Quantity::Float{ v: a+b }},
(Quantity::Float{v:a}, Quantity::Rational{v:b}) => {Quantity::Float{ v: a+b.to_float() }},
(Quantity::Rational{v:a}, Quantity::Float{v:b}) => {Quantity::Float{ v: a.to_float()+b }},
(Quantity::Rational{v:a}, Quantity::Rational{v:b}) => {Quantity::Rational{ v: a+b }},
}
}
}
impl AddAssign for Quantity where {
fn add_assign(&mut self, other: Self) {
match (&mut *self, other) {
(Quantity::Float{v: a}, Quantity::Float{v: ref b}) => {*a += b},
(Quantity::Float{v: a}, Quantity::Rational{v:b}) => {*a += b.to_float()},
(Quantity::Rational{v:a}, Quantity::Float{v:b}) => {*self = Quantity::Float{ v: a.to_float()+b }},
(Quantity::Rational{v:a}, Quantity::Rational{v:b}) => {*a += b},
}
}
}
impl Sub for Quantity {
type Output = Self;
fn sub(self, other: Self) -> Self::Output {
match (self, other) {
(Quantity::Float{v:a}, Quantity::Float{v:b}) => {Quantity::Float{ v: a-b }},
(Quantity::Float{v:a}, Quantity::Rational{v:b}) => {Quantity::Float{ v: a-b.to_float() }},
(Quantity::Rational{v:a}, Quantity::Float{v:b}) => {Quantity::Float{ v: a.to_float()-b }},
(Quantity::Rational{v:a}, Quantity::Rational{v:b}) => {Quantity::Rational{ v: a-b }},
}
}
}
impl SubAssign for Quantity where {
fn sub_assign(&mut self, other: Self) {
match (&mut *self, other) {
(Quantity::Float{v: a}, Quantity::Float{v: ref b}) => {*a -= b},
(Quantity::Float{v: a}, Quantity::Rational{v:b}) => {*a -= b.to_float()},
(Quantity::Rational{v:a}, Quantity::Float{v:b}) => {*self = Quantity::Float{ v: a.to_float()-b }},
(Quantity::Rational{v:a}, Quantity::Rational{v:b}) => {*a -= b},
}
}
}
impl Mul for Quantity {
type Output = Self;
fn mul(self, other: Self) -> Self::Output {
match (self, other) {
(Quantity::Float{v:a}, Quantity::Float{v:b}) => {Quantity::Float{ v: a*b }},
(Quantity::Float{v:a}, Quantity::Rational{v:b}) => {Quantity::Float{ v: a*b.to_float() }},
(Quantity::Rational{v:a}, Quantity::Float{v:b}) => {Quantity::Float{ v: a.to_float()*b }},
(Quantity::Rational{v:a}, Quantity::Rational{v:b}) => {Quantity::Rational{ v: a*b }},
}
}
}
impl MulAssign for Quantity where {
fn mul_assign(&mut self, other: Self) {
match (&mut *self, other) {
(Quantity::Float{v: a}, Quantity::Float{v: ref b}) => {*a *= b},
(Quantity::Float{v: a}, Quantity::Rational{v:b}) => {*a *= b.to_float()},
(Quantity::Rational{v:a}, Quantity::Float{v:b}) => {*self = Quantity::Float{ v: a.to_float() * b }},
(Quantity::Rational{v:a}, Quantity::Rational{v:b}) => {*a *= b},
}
}
}
impl Div for Quantity {
type Output = Self;
fn div(self, other: Self) -> Self::Output {
match (self, other) {
(Quantity::Float{v:a}, Quantity::Float{v:b}) => {Quantity::Float{ v: a/b }},
(Quantity::Float{v:a}, Quantity::Rational{v:b}) => {Quantity::Float{ v: a/b.to_float() }},
(Quantity::Rational{v:a}, Quantity::Float{v:b}) => {Quantity::Float{ v: a.to_float()/b }},
(Quantity::Rational{v:a}, Quantity::Rational{v:b}) => {Quantity::Rational{ v: a/b }},
}
}
}
impl DivAssign for Quantity where {
fn div_assign(&mut self, other: Self) {
match (&mut *self, other) {
(Quantity::Float{v: a}, Quantity::Float{v: ref b}) => {*a /= b},
(Quantity::Float{v: a}, Quantity::Rational{v:b}) => {*a /= b.to_float()},
(Quantity::Rational{v:a}, Quantity::Float{v:b}) => {*self = Quantity::Float{ v: a.to_float()/b }},
(Quantity::Rational{v:a}, Quantity::Rational{v:b}) => {*a /= b},
}
}
}
impl Rem<Quantity> for Quantity {
type Output = Self;
fn rem(self, modulus: Quantity) -> Self::Output {
match (self, modulus) {
(Quantity::Float{v:a}, Quantity::Float{v:b}) => {Quantity::Float{ v: a%b }},
(Quantity::Float{v:a}, Quantity::Rational{v:b}) => {Quantity::Float{ v: a%b.to_float() }},
(Quantity::Rational{v:a}, Quantity::Float{v:b}) => {Quantity::Float{ v: a.to_float()%b }},
(Quantity::Rational{v:a}, Quantity::Rational{v:b}) => {Quantity::Rational { v: a%b }},
}
}
}
impl PartialEq for Quantity {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Quantity::Float{v:a}, Quantity::Float{v:b}) => {a == b},
(Quantity::Float{v:a}, Quantity::Rational{v:b}) => {*a==b.to_float()},
(Quantity::Rational{v:a}, Quantity::Float{v:b}) => {a.to_float()==*b},
(Quantity::Rational{v:a}, Quantity::Rational{v:b}) => {a == b},
}
}
}
impl PartialOrd for Quantity {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
match (self, other) {
(Quantity::Float{v:a}, Quantity::Float{v:b}) => {a.partial_cmp(b)},
(Quantity::Float{v:a}, Quantity::Rational{v:b}) => {(*a).partial_cmp(&b.to_float())},
(Quantity::Rational{v:a}, Quantity::Float{v:b}) => {a.to_float().partial_cmp(b)},
(Quantity::Rational{v:a}, Quantity::Rational{v:b}) => {a.partial_cmp(b)},
}
}
}

216
src/quantity/rationalq.rs Normal file
View File

@ -0,0 +1,216 @@
use rug::Float;
use rug::ops::Pow;
use rug::Rational;
use rug::Integer;
use std::ops::{
Add, Sub, Mul, Div,
Neg, Rem,
AddAssign, SubAssign,
MulAssign, DivAssign
};
use std::cmp::Ordering;
use crate::quantity::Quantity;
use crate::quantity::FLOAT_PRECISION;
macro_rules! rational {
( $x:expr ) => {
Quantity::Rational { v: RationalQ {
val : $x
}}
};
}
macro_rules! float {
( $x:expr ) => {
Quantity::Float { v: $x }
};
}
#[derive(Debug)]
#[derive(Clone)]
pub struct RationalQ where {
pub val: Rational
}
impl ToString for RationalQ {
fn to_string(&self) -> String {
self.to_float().to_string()
}
}
impl RationalQ {
pub fn new(top: i64, bot: i64) -> RationalQ {
return RationalQ {
val: Rational::from((top, bot))
}
}
pub fn is_zero(&self) -> bool{
return self.val == Rational::from((0,1));
}
pub fn fract(&self) -> Quantity {
rational!(self.val.clone().fract_floor(Integer::new()).0)
}
pub fn from_f64(f: f64) -> Option<RationalQ> {
let v = Rational::from_f64(f);
if v.is_none() { return None }
return Some(RationalQ{ val: v.unwrap() });
}
pub fn to_float(&self) -> Float {
Float::with_val(FLOAT_PRECISION, self.val.numer()) /
Float::with_val(FLOAT_PRECISION, self.val.denom())
}
pub fn to_string_radix(&self, radix: i32, num_digits: Option<usize>) -> String {
self.to_float().to_string_radix(radix, num_digits)
}
pub fn to_sign_string_exp(&self, radix: i32, num_digits: Option<usize>) -> (bool, String, Option<i32>) {
self.to_float().to_sign_string_exp(radix, num_digits)
}
pub fn abs(&self) -> Quantity {rational!(self.val.clone().abs())}
pub fn floor(&self) -> Quantity {rational!(self.val.clone().floor())}
pub fn ceil(&self) -> Quantity {rational!(self.val.clone().ceil())}
pub fn round(&self) -> Quantity {rational!(self.val.clone().round())}
pub fn sin(&self) -> Quantity {float!(self.to_float().sin())}
pub fn cos(&self) -> Quantity {float!(self.to_float().cos())}
pub fn tan(&self) -> Quantity {float!(self.to_float().tan())}
pub fn asin(&self) -> Quantity {float!(self.to_float().asin())}
pub fn acos(&self) -> Quantity {float!(self.to_float().acos())}
pub fn atan(&self) -> Quantity {float!(self.to_float().atan())}
pub fn sinh(&self) -> Quantity {float!(self.to_float().sinh())}
pub fn cosh(&self) -> Quantity {float!(self.to_float().cosh())}
pub fn tanh(&self) -> Quantity {float!(self.to_float().tanh())}
pub fn asinh(&self) -> Quantity {float!(self.to_float().asinh())}
pub fn acosh(&self) -> Quantity {float!(self.to_float().acosh())}
pub fn atanh(&self) -> Quantity {float!(self.to_float().atanh())}
pub fn ln(&self) -> Quantity {float!(self.to_float().ln())}
pub fn log10(&self) -> Quantity {float!(self.to_float().log10())}
pub fn log2(&self) -> Quantity {float!(self.to_float().log2())}
pub fn log(&self, base: Quantity) -> Quantity {
float!(self.to_float().log10() / base.to_float().log10())
}
pub fn pow(&self, exp: Quantity) -> Quantity {
float!(self.to_float().pow(exp.to_float()))
}
}
impl Add for RationalQ where {
type Output = Self;
fn add(self, other: Self) -> Self::Output {
Self {
val: self.val + other.val
}
}
}
impl AddAssign for RationalQ where {
fn add_assign(&mut self, other: Self) {
self.val += other.val;
}
}
impl Sub for RationalQ {
type Output = Self;
fn sub(self, other: Self) -> Self::Output {
Self {
val: self.val - other.val
}
}
}
impl SubAssign for RationalQ where {
fn sub_assign(&mut self, other: Self) {
self.val -= other.val;
}
}
impl Mul for RationalQ {
type Output = Self;
fn mul(self, other: Self) -> Self::Output {
Self {
val: self.val * other.val
}
}
}
impl MulAssign for RationalQ where {
fn mul_assign(&mut self, other: Self) {
self.val *= other.val;
}
}
impl Div for RationalQ {
type Output = Self;
fn div(self, other: Self) -> Self::Output {
Self {
val: self.val / other.val
}
}
}
impl DivAssign for RationalQ where {
fn div_assign(&mut self, other: Self) {
self.val /= other.val;
}
}
impl Neg for RationalQ where {
type Output = Self;
fn neg(self) -> Self::Output {
Self {
val: -self.val
}
}
}
impl Rem<RationalQ> for RationalQ {
type Output = Self;
fn rem(self, modulus: RationalQ) -> Self::Output {
if {
*self.val.denom() != 1 ||
*modulus.val.denom() != 1
} { panic!() }
RationalQ{
val : Rational::from((
self.val.numer() % modulus.val.numer(),
1
))
}
}
}
impl PartialEq for RationalQ {
fn eq(&self, other: &Self) -> bool {
self.val == other.val
}
}
impl PartialOrd for RationalQ {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.val.partial_cmp(&other.val)
}
}