简体   繁体   中英

Python error: could not broadcast input array from shape (20,10) into shape (10)

I have the following code and get this error: S[i+1,:] = (S[i,:] + np.cumsum(np.sqrt(dt) np.random.randn(nsims),axis=0)) + epsilon_plus np.random.poisson(lambda_plus,(M,nsims))

ValueError: could not broadcast input array from shape (20,10) into shape (10)

sigma = 0.1
dt = 0.05
lambda_plus = 2
lambda_minus = 2
M = 20 #number of steps
epsilon_plus = 1.0/2
epsilon_minus = 1.0/2   
T = 1
nsims = 10
s = 100
S = s*np.ones((M,nsims))

def price(lambda_plus, lambda_minus, M, T, dt, nsims):
    for i in range(M-1):
        S[i+1,:]  = (S[i,:] + np.cumsum(np.sqrt(dt)*np.random.randn(nsims),axis=0)) + epsilon_plus*np.random.poisson(lambda_plus,(M,nsims))
    return S

The error occurs when I add the part of epsilon_plus*np.random.poisson(lambda_plus,(M,nsims)). How can I add this part to S?

The problem is this expression:

S[t-1] + sigma*math.sqrt(dt)*A + epsilon_plus*B-epsilon_minus*C

All three terms you're adding sigma*math.sqrt(dt)*A , epsilon_plus*B , and epsilon_minus*C have shape (201,) , and so does the result after adding to S[t-1] - but you're trying to assign it to S[t] , which has shape (1,) .

You need to explain what exactly you expect to store in S[t] for me to provide a solution - I don't want to reverse engineer / guess intent from your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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