Browse code

add some additional functionality to the state module

Joseph Weston authored on 01/11/2023 04:34:05
Showing 1 changed files
... ...
@@ -10,7 +10,7 @@ by the associated classical bitstring.
10 10
 
11 11
 import numpy as np
12 12
 
13
-__all__ = ["from_classical", "is_normalized", "num_qubits", "zero"]  # type: ignore
13
+__all__ = ["from_classical", "is_normalized", "is_normalizable", "normalize", "num_qubits", "zero"]  # type: ignore
14 14
 
15 15
 
16 16
 def from_classical(bitstring):
... ...
@@ -59,7 +59,22 @@ def num_qubits(state):
59 59
 
60 60
 def is_normalized(state: np.ndarray) -> bool:
61 61
     """Return True if and only if 'state' is normalized."""
62
-    return np.allclose(np.linalg.norm(state), 1)
62
+    return np.isclose(np.linalg.norm(state), 1)
63
+
64
+
65
+def is_normalizable(v: np.ndarray) -> bool:
66
+    """Return True if and only if 'v' is normalizable."""
67
+    # If the norm is too small then normalizing a vector using
68
+    # the norm will yield a vector that is not normalized to machine
69
+    # precision.
70
+    return bool(np.linalg.norm(v) ** 2 > np.finfo(float).smallest_normal)
71
+
72
+
73
+def normalize(state: np.ndarray) -> np.ndarray:
74
+    """Return a normalized state, given a potentially un-normalized one."""
75
+    if not is_normalizable(state):
76
+        raise ValueError("State is not normalizable")
77
+    return state / np.linalg.norm(state)
63 78
 
64 79
 
65 80
 def _check_valid_state(state):