user9990505
user9990505

Reputation:

Finding average of elements with the previous elements and summing it and averaging

I have a set of numbers, just to make it easier:

import numpy as np
A = np.array([0, 1, 2, 3, 4, 5, ...])

I want to:

((0+1)/2 + (2+1)/2)/2 , ((1+2)/2 + (3+2)/2)/2, ....

I am not sure how to go about this. What I got so far:

B = (A[1:]+A[:-1])/2.0

I would expect to get:

B = [1, 2, 3, 4, 5 ...]

Any help would be great. Thank you.

Upvotes: 0

Views: 52

Answers (1)

kevinkayaks
kevinkayaks

Reputation: 2726

>> import numpy as np
>> def pair_avg(a):
>>    return (a[1:]+a[:-1])/2.0
>>
>> a = np.arange(10)
>> pair_avg(pair_avg(a))
array([1., 2., 3., 4., 5., 6., 7., 8.])

pair_avg does a running average of every pair in a. As I understand you want to do this twice. I think you should see this operation as a recursive application of the same function. If you always want to recurse twice, you can do

>> def oper(a):
>>    b = (a[1:]+a[:-1])/2.0
>>    return (b[1:]+b[:-1])/2.0
>>
>> oper(a)
array([1., 2., 3., 4., 5., 6., 7., 8.])

Of course, this is equivalent to some weighted sum of the original array elements. Every 2nd application of pair_avg will just clip off two more end point values of the original array when you apply it to integers.

Upvotes: 1

Related Questions