Issue
I have two arrays of arbitrary length:
a = [1,2,3]
b = [4,5]
I want the average of all fractions x/y
where x
is from a
and y
is from b
i.e. avg(1/4 + 1/5 + 2/4 + 2/5 +...) = 0.45
in this case.
I would like to avoid using loops, and stick to numpy functions. I have found a solution using np.meshgrid
:
numerator = a
denominator = 1/b
pairs = np.array(np.meshgrid(numerator, denominator)).T.reshape(-1,2)
>>> array([[1. , 0.25],
[1. , 0.2 ],
[2. , 0.25],
[2. , 0.2 ],
[3. , 0.25],
[3. , 0.2 ]])
fractions = np.multiply.reduce(pairs, axis=1)
>>> array([0.25, 0.2 , 0.5 , 0.4 , 0.75, 0.6 ])
result = np.mean(fractions)
>>> 0.45 # Correct
I would like to know if there is a more elegant (mathematical?) way of achieving the result I want. Help is much appreciated.
Solution
You can first determine the sum of all items, and then divide that sum by the items in b
to determine the mean:
>>> a = np.array([1,2,3])
>>> b = np.array([4,5])
>>> (a.mean() / b).mean()
0.45
The advantage of first calculating the mean of the numerators, is that this algorithm takes linear time (O(|a| + |b|)), instead of quadratic time (O(|a|×|b|)).
Answered By - Willem Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.