Added nounit and tobase functions

This commit is contained in:
2023-06-14 09:24:34 -07:00
parent aa02b35cc5
commit 061f58ba53
6 changed files with 83 additions and 35 deletions

View File

@ -99,16 +99,19 @@ impl Quantity {
pub fn insert_unit(&mut self, ui: FreeUnit, pi: Scalar) { self.unit.insert(ui, pi) }
pub fn set_unit(&mut self, u: Unit) { self.unit = u; }
pub fn without_unit(&self) -> Quantity { Quantity::from_scalar(self.scalar.clone()) }
pub fn convert_to(self, other: Quantity) -> Option<Quantity> {
pub fn convert_to(&self, other: Quantity) -> Option<Quantity> {
if !self.unit.compatible_with(&other.unit) { return None; }
let n = self.clone();
let fa = self.unit.to_base_factor();
let fb = other.unit.to_base_factor();
return Some(self.mul_no_convert(fa).div_no_convert(fb))
return Some(n.mul_no_convert(fa).div_no_convert(fb))
}
pub fn convert_to_base(&self) -> Quantity { self.convert_to(self.unit.to_base()).unwrap() }
}

View File

@ -51,7 +51,7 @@ impl FreeUnit {
}
// Get this unit in terms of base units
pub fn get_base(&self) -> Quantity {
pub fn to_base(&self) -> Quantity {
let q = self.whole.base_factor();
let mut q = q.unwrap_or(Quantity::new_rational_from_string("1").unwrap());

View File

@ -123,7 +123,7 @@ impl Unit {
flag = false;
for (uo, po) in other.get_val() {
if {
us.get_base().unit.compatible_with(&uo.get_base().unit)
us.to_base().unit.compatible_with(&uo.to_base().unit)
} {
factor.insert_unit(us.clone(), po.clone());
flag = true;
@ -141,7 +141,7 @@ impl Unit {
flag = false;
for (us, _) in self.get_val() {
if {
us.get_base().unit.compatible_with(&uo.get_base().unit)
us.to_base().unit.compatible_with(&uo.to_base().unit)
} {
factor.insert_unit(us.clone(), po.clone());
flag = true;
@ -186,11 +186,21 @@ impl Unit {
return q;
}
pub fn to_base(&self) -> Quantity {
let mut q = Quantity::new_rational(1f64).unwrap();
for (u, p) in self.get_val().iter() {
let b = u.to_base();
q.mul_assign_no_convert(b.pow(Quantity::from_scalar(p.clone())));
}
return q;
}
}
impl Unit {
pub fn from_string(s: &str) -> Option<Quantity> {
let b = freeunit_from_string(s);
if b.is_none() { return None; }
let b = Unit::from_free(b.unwrap());