Skip to content

Commit

Permalink
Unit.factorless is always correct
Browse files Browse the repository at this point in the history
  • Loading branch information
chaoming0625 committed Dec 11, 2024
1 parent 96060a8 commit 5585c9a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
28 changes: 24 additions & 4 deletions brainunit/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1534,12 +1534,32 @@ def dispname(self, dispname):
"Please create a new Unit object with the dispname you want."
)

def factorless(self):
def factorless(self) -> 'Unit':
"""
Return a copy of this Unit with the factor set to 1.
Returns
-------
Unit
A new Unit object with the factor set to 1.
"""
# using standard units
key = (self.dim, self.scale, self.base, 1.)
if key in _standard_units:
return _standard_units[key]
else:
raise ValueError(f"Cannot find a factorless unit for {self}")

# using temporary units
name, is_fullname, dimless = _find_standard_unit(self.dim, self.base, self.scale, 1.0)
return Unit(
dim=self.dim,
scale=self.scale,
base=self.base,
factor=1.,
name=name,
dispname=name,
iscompound=self.iscompound,
is_fullname=is_fullname,
)

def copy(self):
"""
Expand Down Expand Up @@ -2532,7 +2552,7 @@ def factorless(self) -> 'Quantity':
The Quantity object without the factor.
"""
if self.unit.factor != 1.0:
return Quantity(self.mantissa / self.unit.factor, unit=self.unit.factorless())
return Quantity(self.mantissa * self.unit.factor, unit=self.unit.factorless())
else:
return self

Expand Down
4 changes: 4 additions & 0 deletions brainunit/_base_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,10 @@ def test_display(self):
print(str(u.kmeter / u.meter))
assert_equal(str(u.kmeter / u.meter), 'Unit(10.0^3)')

def test_unit_with_factor(self):
self.assertTrue(1. * u.eV / u.joule == 1.6021765e-19)
self.assertTrue(1. * u.joule / u.eV == 6.241509074460762e18)


class TestQuantity(unittest.TestCase):
def test_dim(self):
Expand Down

0 comments on commit 5585c9a

Please sign in to comment.