Summation Evaluation in python

Summation Evaluation in python

I think this might be what youre looking for:

sum(z_i**k * math.exp(-z_i**2 / 2) for z_i in z)

If you want to vectorize calculations with numpy, you need to use numpys ufuncs. Also, the usual way of doing you calculation would be:

import numpy as np

calc = np.sum(z**k * np.exp(-z*z / 2))

although you can keep your approach using if you call np.exp instead of math.exp:

calc =**k, np.exp(-z*z / 2))

It does run faster with dot:

In [1]: z = np.random.rand(1000)

In [2]: %timeit np.sum(z**5 * np.exp(-z*z / 2))
10000 loops, best of 3: 142 µs per loop

In [3]: %timeit**5, np.exp(-z*z / 2))
1000 loops, best of 3: 129 µs per loop

In [4]: np.allclose(np.sum(z**5 * np.exp(-z*z / 2)),
...       **5, np.exp(-z*z / 2)))
Out[4]: True

Summation Evaluation in python

def myfun(z_i):
    return z_i**k * math.exp(-z_i**2 / 2)

We define a function for the thing we want to sum, use the map function to apply it to each value in the list and then sum all these values. Having to use an external variable k is slightly niggling.

A refinement would be to define a two argument function

def myfun2(z_i,k):
    return z_i**k * math.exp(-z_i**2 / 2)

and use a lambda expression to evaluate it

sum(map(lambda x:myfun2(x,1), z))

Leave a Reply

Your email address will not be published. Required fields are marked *