Skip to content

Commit cbf3579

Browse files
committed
Add unary negation.
1 parent f6a6bda commit cbf3579

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
175175
### [Unreleased]
176176
#### Added
177177
- Add computation of unit powers in C++ and Python.
178+
- Add unary negation operator to `Quantity`.
178179

179180
#### Changed
180181
- Fix array values of `Quantity` with dimension larger than one causing

cyantities/quantity.pyx

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -618,6 +618,25 @@ cdef class Quantity:
618618
return _power_quantity(self, exponent)
619619

620620

621+
def __neg__(self):
622+
"""
623+
Unary negative.
624+
"""
625+
# Mostly a copy, we just have to see which part of the value
626+
# (scalar or ndarray?) we have to negate:
627+
cdef Quantity res = Quantity.__new__(Quantity)
628+
if self._is_scalar:
629+
res._cyinit(
630+
True, -self._val, None, self._unit
631+
)
632+
else:
633+
res._cyinit(
634+
False, dummy_double[0], -self._val_object, self._unit
635+
)
636+
637+
return res
638+
639+
621640
def __eq__(self, other):
622641
# First the case that the other is not a Quantity.
623642
# This results in nonzero only if this quantity is

testing/test_quantities.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,8 +76,10 @@ def test_quantity():
7676
assert np.all(q6 == Quantity(np.array([1.0, 2.0, 3.0]) - 1.0, "m"))
7777
q7 = q0 - q1
7878
assert np.all(q7 == Quantity(1.0 - np.array([1.0, 2.0, 3.0]), "m"))
79+
assert np.all(q7 == -q6)
7980
with pytest.raises(RuntimeError):
8081
q0 - q3
82+
assert q0 - 2*q0 == -q0
8183

8284
# Test conversion of dimensionless Quantities to NumPy arrays:
8385
q8 = q1 / Unit('m')

0 commit comments

Comments
 (0)