Montag, 30. Mai 2011

Python 002: Averaging over values

A common task is to display raw data together with a more informative average value. The figure below shows the energy of a harmonic oscillator together with the average value of the energy at the same time. The values are from a Monte Carlo simulation.
The question is how to generate the list of average values most efficiently. In the present case, I calculated the average over something like nsamples/100 values and plotted a corresponding point. But if I want to let the list of averages be of the same length as the list of raw data points, i naturally will be able to only plot the first points of the raw data. How is this done correctly?

Eav = array([reduce(lambda x,y: x+y, i)/len(i) for i in [E[i:i+segm] for i in range(0, len(E), segm)]] )

I have been pointed out to a solution making use of the numpy.convolve method.
means = convolve(E, ones(100)/100.0, 'same')

This calculates the average throughout the simulation, instead of only at the end. By doing so, the number of calculated averages is the same as the number of samples. The figure below shows the obtained output.

I only plotted the average now, since the raw data overlays the graphs of the average. What I wonder is why the average at the end drops to zero.

Keine Kommentare:

Kommentar veröffentlichen