From some calculation, I have a distribution of discrete data $ (i,P_i)$ and then want to get the median based on this distribution. Naive way is to create a list
list = Table[Sum[p[[j]], {j, i}], {i, n}]
then find the first element greater than $ 0$ :
pos = Position[list, _?(# >= 0.5 &)][[1, 1]]
but this way is pretty slow, especially when I have a very large amount of data. The reason is I have to do Sum everytime. I did several attempts to speed up, such as
list = Table[0, {i, n}] For[i = 1, i <= n, i ++, list[[i]] = If[i == 1, p[[i]], list[[i - 1]] + p[[i]]]]
or even smarter by using Accumulate
Accumulate[p]
and then do same Position operation. This made everything much faster and I’m pretty happy with it. I’m wondering whether some similar function is already in Mathematica, so we don’t have to manually implement this. However after lookup the Median, I have no results relate to this. Do you guys have any idea?