Skip to content

Ensure the result of simulation is normalized #6522

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 3, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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