mexprp/num/
rugrat.rs

1use std::cmp::Ordering;
2
3use rug::Rational;
4use crate::opers::Calculation;
5use crate::errors::MathError;
6use crate::answer::Answer;
7use crate::num::Num;
8use crate::context::Context;
9
10impl Num for Rational {
11	fn from_f64(t: f64, _ctx: &Context<Self>) -> Calculation<Self> {
12		Ok(Answer::Single(if let Some(r) = Rational::from_f64(t) {
13			r
14		} else {
15			return Err(MathError::Other); // TODO make descriptive
16		}))
17	}
18
19	fn from_f64_complex((r, _i): (f64, f64), _ctx: &Context<Self>) -> Calculation<Self> {
20		Ok(Answer::Single(if let Some(r) = Rational::from_f64(r) {
21			r
22		} else {
23			return Err(MathError::Other); // TODO make descriptive
24		}))
25	}
26
27	fn typename() -> String {
28		String::from("Rational")
29	}
30
31	fn tryord(&self, other: &Self, _ctx: &Context<Self>) -> Result<Ordering, MathError> {
32		if let Some(ord) = self.partial_cmp(other) {
33			Ok(ord)
34		} else {
35			Err(MathError::CmpError)
36		}
37	}
38
39	fn add(&self, other: &Self, _ctx: &Context<Self>) -> Calculation<Self> {
40		let r = Rational::from(self + other);
41
42		Ok(Answer::Single(r))
43	}
44
45	fn sub(&self, other: &Self, _ctx: &Context<Self>) -> Calculation<Self> {
46		let r = Rational::from(self - other);
47
48		Ok(Answer::Single(r))
49	}
50
51	fn mul(&self, other: &Self, _ctx: &Context<Self>) -> Calculation<Self> {
52		let r = Rational::from(self * other);
53
54		Ok(Answer::Single(r))
55	}
56
57	fn div(&self, other: &Self, _ctx: &Context<Self>) -> Calculation<Self> {
58		let r = Rational::from(self / other);
59
60		Ok(Answer::Single(r))
61	}
62	
63	fn abs(&self, _ctx: &Context<Self>) -> Calculation<Self> {
64		let r = Rational::from(self.abs_ref());
65		
66		Ok(Answer::Single(r))
67	}
68	
69	fn floor(&self, _ctx: &Context<Self>) -> Calculation<Self> {
70		let r = Rational::from(self.floor_ref());
71		
72		Ok(Answer::Single(r))
73	}
74	
75	fn ceil(&self, _ctx: &Context<Self>) -> Calculation<Self> {
76		let r = Rational::from(self.ceil_ref());
77		
78		Ok(Answer::Single(r))
79	}
80	
81	fn round(&self, _ctx: &Context<Self>) -> Calculation<Self> {
82		let r = Rational::from(self.round_ref());
83		
84		Ok(Answer::Single(r))
85	}
86}