0

Problem: Calculate the mean and standard deviation of a tightly clustered set of 1000 initial conditions as a function of iteration number. The bunch of initial conditions should be Gaussian distributed about x = 0.3 with a standard deviation of 10-3

The code I wrote:

from numpy import *

def IterateMap(x,r,n):
    for i in xrange(n):
        x = r * x * (1.0 - x)
    return x

output = "data"
nIterations = 1000
r = 4.0
x0 = 0.3
delta = 0.00005

L = []

for i in xrange(nIterations):
    x = x0
    x = IterateMap(x,r,1)
    L[i] = x
    x0 = x0 + delta

A = array(L)

print 'mean: ', mean(A)

So what my code is supposed to do is to take an initial value for x (x0) and call the IterateMap function and return a new value of x and place it in a list(L) then x0 changes to a new value, and this process continues for 1000 times. I get the error "list assignment index out of range". Also, do you think I'm following the problem correctly?

2
  • 1
    Include the full traceback so we don't have to guess where your error occurs, please. Commented Dec 4, 2012 at 7:24
  • 1
    L = [] and then you try to do L[i] = x, there are no elements in the list. ;) Commented Dec 4, 2012 at 7:26

2 Answers 2

2

Python lists do not automatically grow when you address indices beyond it's current size. You created an empty list, so you cannot address any index in it.

Use .append() to add new values to the end of the list:

L.append(x)

Alternatively, you'd have to create a list that can hold all the indices you want to generate instead, by pre-filling it with None or another default value:

L = [None for _ in xrange(nIterations)]
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, btw, I'm now getting an index out of bounds error when I set my nIterations to 1000. However, if I use 500 or 700 it works. Any ideas as to what may cause this?
@Randy: because whatever index you are using at the time of the indexerror is not part of the list.
0

The problem is here:

L = [] # the list is empty!

for i in xrange(nIterations):
    ...
    L[i] = x

To fix, replace L[i] = x with L.append(x).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.