Skip to content

Commit 45c5fa3

Browse files
Ensure the result of simulation is normalized (#6522)
1 parent acb7bf8 commit 45c5fa3

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

cirq-core/cirq/sim/state_vector_simulator.py

+11-1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import abc
1717
from functools import cached_property
1818
from typing import Any, Dict, Iterator, Sequence, Type, TYPE_CHECKING, Generic, TypeVar
19+
import warnings
1920

2021
import numpy as np
2122

@@ -124,7 +125,16 @@ def __init__(
124125

125126
@cached_property
126127
def final_state_vector(self) -> np.ndarray:
127-
return self._get_merged_sim_state().target_tensor.reshape(-1)
128+
ret = self._get_merged_sim_state().target_tensor.reshape(-1)
129+
norm = np.linalg.norm(ret)
130+
if abs(norm - 1) > np.sqrt(np.finfo(ret.dtype).eps):
131+
warnings.warn(
132+
f"final state vector's {norm=} is too far from 1,"
133+
f" {abs(norm-1)} > {np.sqrt(np.finfo(ret.dtype).eps)}."
134+
"skipping renormalization"
135+
)
136+
return ret
137+
return ret / norm
128138

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

0 commit comments

Comments
 (0)