Skip to content

Commit

Permalink
Ensure the result of simulation is normalized (#6522)
Browse files Browse the repository at this point in the history
  • Loading branch information
NoureldinYosri authored Apr 3, 2024
1 parent acb7bf8 commit 45c5fa3
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion cirq-core/cirq/sim/state_vector_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import abc
from functools import cached_property
from typing import Any, Dict, Iterator, Sequence, Type, TYPE_CHECKING, Generic, TypeVar
import warnings

import numpy as np

Expand Down Expand Up @@ -124,7 +125,16 @@ def __init__(

@cached_property
def final_state_vector(self) -> np.ndarray:
return self._get_merged_sim_state().target_tensor.reshape(-1)
ret = self._get_merged_sim_state().target_tensor.reshape(-1)
norm = np.linalg.norm(ret)
if abs(norm - 1) > np.sqrt(np.finfo(ret.dtype).eps):
warnings.warn(
f"final state vector's {norm=} is too far from 1,"
f" {abs(norm-1)} > {np.sqrt(np.finfo(ret.dtype).eps)}."
"skipping renormalization"
)
return ret
return ret / norm

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

0 comments on commit 45c5fa3

Please sign in to comment.