Skip to content

Commit d16b12c

Browse files
authored
Avoid state vector normalization if it worsens the round offs (#6556)
This fixes failure of check/pytest -n0 cirq-core/cirq/circuits/circuit_test.py::test_final_state_vector which happened because normalization of a state vector at `np.complex64` precision can subtly increase the overall round-off error. Follow up to #6522 and #6402
1 parent c18feed commit d16b12c

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

cirq-core/cirq/sim/state_vector_simulator.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,11 @@ def final_state_vector(self) -> np.ndarray:
134134
"skipping renormalization"
135135
)
136136
return ret
137-
return ret / norm
137+
# normalize only if doing so improves the round-off on total probability
138+
ret_norm = ret / norm
139+
round_off_change = abs(np.vdot(ret_norm, ret_norm) - 1) - abs(np.vdot(ret, ret) - 1)
140+
result = ret_norm if round_off_change < 0 else ret
141+
return result
138142

139143
def state_vector(self, copy: bool = False) -> np.ndarray:
140144
"""Return the state vector at the end of the computation.

0 commit comments

Comments
 (0)