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) 
  • $\begingroup$ Does the indentation(second line) look ok? It seems off... could that be the reason? $\endgroup$ – Hasan Iqbal May 18 at 20:56
  • 3
    $\begingroup$ Avoid using "sum" as a variable name because Python has a built-in function with that name. You may use "_sum" instead $\endgroup$ – Egretta.Thula May 18 at 21:39
  • $\begingroup$ 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! $\endgroup$ – user1271772 May 28 at 17:53

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())


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

which is what you expected.

  • $\begingroup$ I think in the for loop you want matrix += y*np.outer(x,x) $\endgroup$ – forky40 May 18 at 21:41
  • $\begingroup$ yeah. my bad :) $\endgroup$ – KAJ226 May 18 at 21:52
  • $\begingroup$ 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. $\endgroup$ – Adam Zalcman May 18 at 22:04
  • 1
    $\begingroup$ @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! $\endgroup$ – KAJ226 May 18 at 22:06
  • $\begingroup$ 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) . $\endgroup$ – John Jones May 18 at 22:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.