# How to code density matrix in python? [closed]

how to do this in python using for loop $$\rho = \sum_i p(x)|x\rangle\langle x|$$ where $$X = {x1,x2,....}$$ and $$P = {p1,p2,p3...}$$ i have tried this loop but tis not working

for x,y in zip(prob,kets):

sum += x * np.outer(y,y)
print(sum)

• Does the indentation(second line) look ok? It seems off... could that be the reason? – Hasan Iqbal May 18 at 20:56
• Avoid using "sum" as a variable name because Python has a built-in function with that name. You may use "_sum" instead – Egretta.Thula May 18 at 21:39
• If you don't understand what |aXa| means, then you could ask that here; but if you understand what it means and you don't know how to do it in Python, I don't see why you wouldn't just ask the question on StackOverflow. I have plenty of times tried to keep questions like this left "open" and was outnumbered by the community, that seems to just not want "pure programming" questions here. So that's why the question got closed, sorry! – user1271772 May 28 at 17:53

## 1 Answer

Not sure if this question is appropriate here in this community...

Regarding to the question, it seems like what you have written should work... unless the way you define x,y and sum have issues. And as one of the comment pointed out, sum, is a built-in function in python so avoid to use it. So here is an example that might help:

import numpy as np
zero = np.matrix([1,0])
one = np.matrix([0,1])
kets = [zero, one]
probs = [1/3, 2/3 ]
matrix = np.zeros( (2,2))
for x,y in zip(kets, probs):
matrix += y*np.outer(x, x.conj())
print(matrix)


ouput

[[0.33333333 0.        ]
[0.         0.66666667]]


which is what you expected.

• I think in the for loop you want matrix += y*np.outer(x,x) – forky40 May 18 at 21:41
• yeah. my bad :) – KAJ226 May 18 at 21:52
• I think the issue might be that np.outer(u, v) computes $uv^T$ even if $u$ and $v$ have complex components. Consequently, the result is not Hermitian. What we want is $uv^\dagger$ which is computed by np.outer(u, v.conj()). Then again, the question does not specify the actual values used, so I can't be sure. – Adam Zalcman May 18 at 22:04
• @AdamZalcman totally... I didn't think of that... just created a simple case to show the OP but I wasn't thinking of complex entries... (facepalm)... Thanks! – KAJ226 May 18 at 22:06
• Thank you for responding, I was using $X = {x1,x2,....}$ each x1,x2.. represents an array $(0,1,2,3),(1,1,1,1)...$ then i was getting an error. operands could not be broadcast together with shapes (2,2) (4,4) (2,2) . – John Jones May 18 at 22:58