diff --git a/quantities/quantity.py b/quantities/quantity.py index e6046fd..74a425f 100644 --- a/quantities/quantity.py +++ b/quantities/quantity.py @@ -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 @@ -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.''' diff --git a/quantities/tests/test_methods.py b/quantities/tests/test_methods.py index ba184a3..ff84210 100644 --- a/quantities/tests/test_methods.py +++ b/quantities/tests/test_methods.py @@ -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)