4
$\begingroup$

I am currently reading a white paper relating to Expectation-Maximisation (EM) and would like to encode a formula so I can play with it in order to help my understanding. The formula in question is a sum over values and shown below;

enter image description here

I am wondering what the advice on the best way to acheive this would be. I am currently thinking about using a for loop to create some kind of cumulative value as I iterate from t = 1 to m.

$\endgroup$
2
  • 2
    $\begingroup$ Have you checked out numpy? docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html $\endgroup$ Commented Jan 31, 2018 at 16:34
  • $\begingroup$ I have not done it, but I would create a python list expression looping through variables (instead of for loops), which is shown to be much faster than traditional for loops. Then use np.cumsum to get cumulative sum. It would be np.cumsum(python_list_expression). Just try on a simple sum! $\endgroup$ Commented Jan 31, 2018 at 16:41

1 Answer 1

3
$\begingroup$

In most cases, I would go for NumPy. Implement a Python function f(t) that calculates the $t$-th summand. Then run

import numpy as np
result = np.array([f(t) for t in range(1,m+1)]).sum()

This will be very fast, unless $m$ is so large that [f(t) for t in range(1,m+1)] does not fit into memory. In this case, I would follow your approach and use a for-loop:

result = 0
for t in range(1, m+1):
    result += f(t)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.