Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summation Evaluation in python

Given z = np.linspace(1,10,100)

Calculate Summation over all values of z in z^k * exp((-z^2)/ 2)

import numpy as np
import math

def calc_Summation1(z, k):
    ans = 0.0
    for i in range(0, len(z)):`
        ans += math.pow(z[i], k) * math.exp(math.pow(-z[i], 2) / 2)
    return ans

def calc_Summation2(z,k):
     part1 = z**k
     part2 = math.exp(-z**2 / 2)
     return np.dot(part1, part2.transpose())

Can someone tell me what is wrong with both calc_Summation1 and calc_Summation2?

like image 986
VeilEclipse Avatar asked Mar 30 '14 06:03

VeilEclipse


2 Answers

I think this might be what you're looking for:

sum(z_i**k * math.exp(-z_i**2 / 2) for z_i in z)
like image 63
rhombidodecahedron Avatar answered Oct 18 '22 05:10

rhombidodecahedron


If you want to vectorize calculations with numpy, you need to use numpy's 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 np.dot if you call np.exp instead of math.exp:

calc = np.dot(z**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 np.dot(z**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)),
...                 np.dot(z**5, np.exp(-z*z / 2)))
Out[4]: True
like image 22
Jaime Avatar answered Oct 18 '22 05:10

Jaime