index 100 is out of bounds for axis 0 with size 100

11,336

Index i goes up to 99 so you are trying to get x[i + 1] == x[100] at the last iteration, so it can not work because x goes up to x[99]

In your for loop just do range(n - 1)

Share:
11,336

Related videos on Youtube

Dennis
Author by

Dennis

Updated on June 04, 2022

Comments

  • Dennis
    Dennis almost 2 years

    I was trying to write a programme using python to compute the infinite series of

    1/1^2 + 1/2^2 + 1/3^2 +1/4^2 +.....

    my code is as follows:

    n = 100
    x = np.zeros([n])
    x[0] = 0
    for i in range(n):
       x[i+1] = x[i] + 1/float((i+1)**2)
    print x[99]
    

    when I tried to execute the code, it returned something as:

    IndexError: index 100 is out of bounds for axis 0 with size 100

    I would like to know what is wrong with the code. Thanks!:)

    • FHTMitchell
      FHTMitchell almost 6 years
      Why are you using a numpy array? Being iterated over is not what they are good at; you'd save yourself a headache just by using a python list and .append.
    • Dennis
      Dennis almost 6 years
      @FHTMitchell First of all, thank you for your ans. It helps. I used numpy array because I have been using this all the time. Can you suggest why list and .append would be more convenient? Is it about the computation time?
    • FHTMitchell
      FHTMitchell almost 6 years
      No, it would stop you making the mistake you made though. Lists are all about dynamically changing size, whereas with a numpy array you have to predict the size of the array (which causes errors exactly like you had).