computable_real/
approx.rs

1use num::BigInt;
2use std::ops::{Add, Mul};
3
4#[derive(Clone, Debug)]
5pub struct Approx {
6    pub value: BigInt,
7    pub precision: i32,
8}
9
10impl Approx {
11    pub fn new(value: &BigInt) -> Self {
12        Self {
13            value: value.clone(),
14            precision: 0,
15        }
16    }
17
18    pub fn prec(&self, precision: i32) -> Self {
19        Self {
20            value: self.value.clone(),
21            precision,
22        }
23    }
24
25    fn scale_by(&self, size: i32) -> Self {
26        Approx {
27            value: super::scale(self.value.clone(), size),
28            precision: self.precision - size,
29        }
30    }
31
32    pub fn scale_to(&self, target: i32) -> Self {
33        self.scale_by(self.precision - target)
34    }
35}
36
37impl Add for Approx {
38    type Output = Self;
39
40    fn add(self, rhs: Self) -> Self {
41        let precision = self.precision.max(rhs.precision);
42        Approx {
43            value: self.value + rhs.value,
44            precision,
45        }
46    }
47}
48
49impl Mul for Approx {
50    type Output = Self;
51
52    fn mul(self, rhs: Self) -> Self {
53        Approx {
54            value: self.value * rhs.value,
55            precision: self.precision + rhs.precision,
56        }
57    }
58}
59
60impl Mul<i32> for Approx {
61    type Output = Self;
62
63    fn mul(self, rhs: i32) -> Self {
64        Approx {
65            value: self.value * rhs,
66            precision: self.precision,
67        }
68    }
69}