diff options
author | Chris Xiong <chirs241097@gmail.com> | 2022-11-07 17:15:15 -0500 |
---|---|---|
committer | Chris Xiong <chirs241097@gmail.com> | 2022-11-07 17:15:15 -0500 |
commit | 7f49730fd8a6dc52fc45937e868749e5612c5234 (patch) | |
tree | 9729ec896e42279f9cc49e862c9405ac60cc6b42 /src/utils.rs | |
download | it2midi-7f49730fd8a6dc52fc45937e868749e5612c5234.tar.xz |
(internal) initial commit
Diffstat (limited to 'src/utils.rs')
-rw-r--r-- | src/utils.rs | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/src/utils.rs b/src/utils.rs new file mode 100644 index 0000000..c53b959 --- /dev/null +++ b/src/utils.rs @@ -0,0 +1,35 @@ +pub struct Rational +{ + n: i64, + d: i64 +} + +fn gcd(a: i64, b: i64) -> i64 +{if b != 0 { gcd(b, a % b) } else { a }} + +impl Default for Rational +{ + fn default() -> Rational { Rational::from_int(0) } +} + +impl Rational +{ + fn from_int(v: i64) -> Rational {Rational{n: v, d: 1}} + fn reduced(self) -> Rational + { + let c = gcd(self.n, self.d); + Rational{n: self.n / c, d: self.d / c} + } + fn add(self, other: Rational) -> Rational + { + let c = gcd(self.d, other.d); + Rational{n: self.n * (other.d / c) + other.n * (self.d / c), + d: self.d / c * other.d}.reduced() + } + fn multiply(self, other: Rational) -> Rational + { + Rational{n: self.n * other.n, d: self.d * other.d}.reduced() + } + fn as_int_trunc(self) -> i64 {self.n / self.d} + fn as_int_round(self) -> i64 {(self.n as f64 / self.d as f64).round() as i64} +} |