# How to represent $|+\rangle$ in Python?

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!

• Should be moved to stackoverflow. Question is about representation of irrational numbers in Python, not related to QC. Jun 19 '19 at 12:43

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