I am using state vectors and operator matrices to test out my knowledge in a Python program. How would I represent the state $|+\rangle$ in Python? I want to then perform several operations in a matrix form on it. I am pretty sure NumPy arrays don't allow for irrational numbers and $|+\rangle$ has a coefficient of $\frac{1}{\sqrt{2}}$ so I am unsure of how to represent this. Should I use fractions? I am new to QC and Python so if anyone has any good suggestions please help out! Thank you!
2 Answers
Just use [0.5**0.5, 0.5**0.5]
, or similarly np.array([np.sqrt(0.5), np.sqrt(0.5)], dtype=np.complex128)
.
Yes, the representation will be approximate instead of exact. Mainly that means you need to use approximate comparison methods like np.allclose
instead of ==
. This is significantly less of a hassle than dealing with exact analytic representations, which will take thousands or millions of times longer to compute while ultimately not being any more informative.
You could either do a numerical approximation
1/math.sqrt(2)
but that would get evaluated to a floating point approximation.
You could do a symbolic expression that is left unevaluated
1/sympy.sqrt(2)
Symbolic results like this can be symbolically simplified with usual rules of mathematics without resorting to calculations with their floating point approximations. This addresses issues of the usual funny things that happen with numerical artifacts.
For example, you could do sympy.sqrt(2)**2