Skip to content

Commit

Permalink
Update and correct pow function for PauliSum (#6019)
Browse files Browse the repository at this point in the history
* Update and correct pow function for PauliSum

Updated pow function for PauliSum to use binary exponentiation

* Format and remainder initialisation correction

+Corrected formatting
+Corrected initialisation of remainder to identity

* Format and remainder initialisation correction

+Corrected formatting
+Corrected initialisation of remainder to identity

* using local variable instead of self and reformatting

* reverting to regular linear multiplication and adding tests

* Adding test for range (1,9)

* trailing blank

* remove trailing blank test

* Getting rid of extraneous variables

* Fix up final formatting issue

---------

Co-authored-by: Tanuj Khattar <tanujkhattar@google.com>
Co-authored-by: Pavol Juhas <juhas@google.com>
  • Loading branch information
3 people committed Mar 21, 2023
1 parent 4607dd1 commit 402260c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
6 changes: 3 additions & 3 deletions cirq-core/cirq/ops/linear_combinations.py
Expand Up @@ -839,10 +839,10 @@ def __pow__(self, exponent: int):
if exponent == 0:
return PauliSum(value.LinearDict({frozenset(): 1 + 0j}))
if exponent > 0:
base = self.copy()
result = self.copy()
for _ in range(exponent - 1):
base *= base
return base
result *= self
return result
return NotImplemented

def __truediv__(self, a: value.Scalar):
Expand Down
16 changes: 16 additions & 0 deletions cirq-core/cirq/ops/linear_combinations_test.py
Expand Up @@ -1156,6 +1156,22 @@ def test_pauli_sum_pow():
for psum in [psum1, psum2, psum3, psum4]:
assert cirq.approx_eq(psum**0, identity)

# tests for exponents greater than two for both even and odd
psum5 = cirq.Z(q0) * cirq.Z(q1) + cirq.Z(q2) + cirq.Z(q3)
correctresult = psum5.copy()
for e in range(1, 9):
assert correctresult == psum5**e
correctresult *= psum5

psum6 = cirq.X(q0) * cirq.Y(q1) + cirq.Z(q2) + cirq.X(q3)
assert psum6 * psum6 * psum6 * psum6 * psum6 * psum6 * psum6 * psum6 == psum6**8

# test to ensure pow doesn't make any change to the original value
psum7 = cirq.X(q0) * cirq.Y(q1) + cirq.Z(q2)
psum7copy = psum7.copy()
assert psum7**5 == psum7 * psum7 * psum7 * psum7 * psum7
assert psum7copy == psum7


# Using the entries of table 1 of https://arxiv.org/abs/1804.09130 as golden values.
@pytest.mark.parametrize(
Expand Down

0 comments on commit 402260c

Please sign in to comment.