Fornax-A
Fornax-A

Reputation: 1032

Mean over a sub-interval Python

I am using Python but since I am noob I can't figure out how to compute the average of a vector each, let's say, 100 elements in a larger for-loop.

My trial so far, which is not what I want is

import numpy as np

r = np.zeros(10000) # declare my vector

for i in range(0,2000): # start the loop
    r[i] = i**2 # some function to compute and save
    if (i%100 == 0): # each time I save 100 elements I want the mean
      av_r = np.mean(r)
      print(av_r)

My code do not work as I want because I would like to make the average of 100 elements only then pass to the other 100, compute the mean and go on.

I try to reduce the dimension of the vector and clean it into the if:

import numpy as np

r = np.zeros(100) # declare my vector

for i in range(0,2000): # start the loop
    r[i] = i**2 # some function to compute and save
    if (i%100 == 0): # each time I save 100 elements I want the mean
      av_r = np.mean(r)
      print(av_r)
      r = np.zeros(100)

naively, I thought you may save 100 elements, compute the average clean the vector and continue the calculation saving the other elements from 100+1 to 200+1 but it give me errors. In particular:

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

Many thanks for your help.

Upvotes: 1

Views: 3001

Answers (2)

Tagc
Tagc

Reputation: 9076

Is this what you're looking for? This code will iterate from 0 to 2000 in intervals of 100, mapping some function (x -> x**2) over each interval, calculating the mean and printing the result.

import numpy as np

r = np.zeros(10000)
for i in range(0, 2000, 100):
    interval = [x ** 2 for x in r[i:i + 100]]
    av_r = np.mean(interval)
    print(av_r)

The output from this is just a series of 20 0.0.

Upvotes: 2

Jean-François Fabre
Jean-François Fabre

Reputation: 140148

the error you probably have encountered is an arrays out of bounds (IndexError: index 100 is out of bounds for axis 0 with size 100), because your index ranges from 0 to 1999 and you're doing

r[i] = i**2 # some function to compute and save

on a 100-sized array.

Fix:

r[i%100] = i**2 # some function to compute and save

Upvotes: 1

Related Questions