🌐 AI搜索 & 代理 主页
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions quantities/quantity.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,16 @@ def _reference(self):

@property
def magnitude(self):
"""
Returns a view onto the numerical value of the quantity, stripping
away the associated units. For example:
```
import quantities as pq
t = 2 * pq.millisecond
n = t.magnitude # n will be 2 (not 0.002)
```
See also: dimensionless_magnitude.
"""
return self.view(type=np.ndarray)

@property
Expand Down Expand Up @@ -250,6 +260,23 @@ def rescale_preferred(self):
raise Exception("Preferred units for '%s' (or equivalent) not specified in "
"quantites.quantity.PREFERRED." % self.dimensionality)

@property
def dimensionless_magnitude(self):
"""
Returns the numerical value of a dimensionless quantity in the form of
a numpy array. Any decimal prefixes are normalized away first.
For example:
```
import quantities as pq
t = 2 * pq.ms
f = 3 * pq.MHz
n = (t*f).dimensionless_magnitude # n will be 6000 (not 6)
```
If the quantity is not dimensionless, a conversion error is raised.
See also: magnitude.
"""
return self.rescale(unit_registry['dimensionless']).magnitude

@with_doc(np.ndarray.astype)
def astype(self, dtype=None, **kwargs):
'''Scalars are returned as scalar Quantity arrays.'''
Expand Down
7 changes: 7 additions & 0 deletions quantities/tests/test_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,3 +356,10 @@ def test_rescale_integer_argument(self):
Quantity(10, pq.deg).rescale(pq.rad),
np.pi/18*pq.rad
)

def test_dimensionless_magnitude(self):
self.assertEqual((pq.kg/pq.g).dimensionless_magnitude, 1000)
self.assertQuantityEqual((self.q / pq.cm).dimensionless_magnitude,
100 * self.q.magnitude)
self.assertRaises(ValueError, lambda x: x.dimensionless_magnitude,
self.q)
Loading