MrFizz
MrFizz

Reputation: 1

How to fix: Having problems with the resulting array of a for-loop equation

I have the following for-loop:

T = 100
mu = 10
var = 3
e = np.array(np.random.normal(mu, var, T+1))

yt = np.array([10])
for i in range(1,T+1):
    ythat = 10 + (0.5 * (yt[i-1] - 10)) + e
    yt = np.append(yt,ythat)

len(yt)

The result of len(yt) is 10101, however I am only trying to append the numpy array with 100 iterations of the loop.

Note: My goal with the 'yt[i-1]' in the middle is to get the result of the previous iteration of the 'ythat' formula.

Upvotes: 0

Views: 55

Answers (2)

Akaisteph7
Akaisteph7

Reputation: 6554

I think you should use a list as calling append on a numpy array will not always give you what you expect but is also pretty computationally expensive. Change your code to:

T = 100
mu = 10
var = 3
e = np.array(np.random.normal(mu, var, T+1))

yt = [10]
for i in range(1,T+1):
    ythat = 10 + (0.5 * (yt[i-1] - 10)) + e
    yt.append(ythat)

len(yt)

Note that yt cannot be converted to a numpy array as the dimensions do not match for all of its elements.

Upvotes: 1

Barmar
Barmar

Reputation: 782683

You need to specify the axis to append on. Without an axis, np.append() will flatten the arrays and concatenate them. To add a new row to the array, use

yt = np.append(yt, ythat, axis=0)

You also need to make the original yt array 2-dimensional:

yt = np.array([10 + e])

Upvotes: 0

Related Questions