nexsys_math/lib.rs
1mod linalg;
2mod mvcalc;
3mod nxn;
4
5pub use crate::linalg::*;
6pub use crate::mvcalc::*;
7pub use crate::nxn::*;
8
9/// Effectively an `f64`, but with an optional domain that the value must be on.
10#[derive(Clone)]
11#[derive(Debug)]
12#[derive(PartialEq)]
13pub struct Variable {
14 value: f64,
15 domain: Option<[f64; 2]>
16}
17impl Variable {
18 /// Instantiates a new `Variable` struct with a specified value and domain.
19 pub fn new(value: f64, domain:Option<[f64; 2]>) -> Variable {
20 Variable {
21 value,
22 domain,
23 }
24 }
25
26 /// Allows the ability to mutate `self.value` if the new value is on `self.domain`.
27 pub fn change(&mut self, qty: f64) {
28 match self.domain {
29 Some(bounds) => {
30 if bounds[0] < qty && qty < bounds[1] {
31 self.value = qty;
32 } else if bounds[0] > qty { // if qty is o.o.b., then move self.value to the bound
33 self.value = bounds[0];
34 } else {
35 self.value = bounds[1];
36 }
37 }
38 None => {
39 // This comment is here exclusively to commemorate the STUPIDEST bug I have ever written:
40 // self.value += qty; <- note how the variable's value is increased instead of changed
41 // ~~ if no domain is specified.
42 self.value = qty;
43 }
44 }
45 }
46
47 /// Mutates the domain of a variable.
48 pub fn change_domain(&mut self, dmn: Option<[f64; 2]>) {
49 self.domain = dmn;
50 }
51
52 /// Allows the ability to mutate `self.value` by adding `qty` to it if the sum of `self.value` and `qty` is on `self.domain`.
53 pub fn step(&mut self, qty: f64) {
54 match self.domain {
55 Some(bounds) => {
56 if bounds[0] < self.value + qty && self.value + qty < bounds[1] {
57 self.value += qty;
58 } else if bounds[0] > self.value + qty { // if qty is o.o.b., then move self.value to the bound
59 self.value = bounds[0];
60 } else {
61 self.value = bounds[1];
62 }
63 }
64 None => {
65 self.value += qty; // IT'S. THIS. LINE. EVERY. GODDAMN. TIME.
66 }
67 }
68 }
69
70 /// Returns `self.value` as `f64`.
71 pub fn as_f64(&self) -> f64 {
72 self.value
73 }
74}