简体   繁体   English

函数内部的 For 循环无法迭代变量

[英]For-loop inside function couldn't iterate the variables

I'm willing to compute all values of all of variables combinations.我愿意计算所有变量组合的所有值。 However, the code always produces the same values for all iterations.但是,代码始终为所有迭代生成相同的值。

#chsh
import numpy as np
from bell_state import bell_state
from pauli import pauli

#setup of measurement

N_A = 2  #measurement outcomes
N_B = 2 

#Bell_state used
rho = bell_state(1)

#Alice 

A_1 =pauli('Z')
A_2 =pauli('X')

#Bob

B_1 =(1/np.sqrt(2))*(pauli('Z')+pauli('X'))
B_2 =(1/np.sqrt(2))*(pauli('Z')-pauli('X'))

def AB(a,b):
    if a==1 and b==1:
        aabb = np.kron(A_1,B_1)
    elif a==2 and b==1:
        aabb = np.kron(A_2,B_1)
    elif a==1 and b==2:
        aabb = np.kron(A_1,B_2)
    elif a==2 and b==2:
        aabb = np.kron(A_2,B_2)
    else:
        print('error')
    return aabb

def Obs(a,b):
    for a in range(1,N_A):
        for b in range(1,N_B):
            ob =np.trace(np.dot(AB(a,b),rho))
            return ob

IObs = Obs(1,1) + Obs(1,2) + Obs(2,1) - Obs(2,2)

The code showed this results, those not what I want代码显示了这个结果,那些不是我想要的

Obs(1,1) : 0.7071067811865475 
 Obs(2,1) : 0.7071067811865475 
 Obs(1,2) : 0.7071067811865475 
 Obs(2,2) : 0.7071067811865475 

IObs : 
 1.414213562373095

The results what I expected actually as same as the results that (I computed manually without loops by this below code结果实际上与我预期的结果相同(我通过以下代码在没有循环的情况下手动计算

Ob11= np.trace(np.dot(AB(1,1),rho))
Ob21= np.trace(np.dot(AB(2,1),rho))
Ob12= np.trace(np.dot(AB(1,2),rho))
Ob22= np.trace(np.dot(AB(2,2),rho))

results of what I want我想要的结果

Obs(1,1)  : 0.7071067811865475 
Obs(2,1)  : 0.7071067811865475 
Obs(1,2)  : 0.7071067811865475 
Obs(2,2)  : -0.7071067811865475 

IObs : 
 2.82842712474619

Perhaps somebody could help me find what I've done wrong with my for-loop function.也许有人可以帮助我找出我的 for 循环函数做错了什么。 Thank you!谢谢!

I think the issue is in Obs function here我认为问题出在此处的 Obs 函数中

def Obs(a,b):
    for a in range(1,N_A):
        for b in range(1,N_B):
            ob =np.trace(np.dot(AB(a,b),rho))
            return ob

As you might see, the return statement is placed inside the loop block.如您所见,return 语句位于循环块内。 This makes your code for calculating ob is never executed more than 1, in other word, it is executed exactly once for whatever a and b you pass to the function.这使得您计算 ob 的代码永远不会执行超过 1 次,换句话说,对于您传递给函数的任何ab ,它都只执行一次。

Based on my assumption (cause I am not too sure about the logic you wanted to implement), you may want to try to use this instead:根据我的假设(因为我不太确定你想要实现的逻辑),你可能想尝试使用它:

def Obs(a,b):
    for a in range(1,N_A):
        for b in range(1,N_B):
            ob =np.trace(np.dot(AB(a,b),rho))
    return ob

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM