python中的求和求值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22740812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:33:56  来源:igfitidea点击:

Summation Evaluation in python

pythonpython-2.7mathnumpy

提问by VeilEclipse

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

给定的 z = np.linspace(1,10,100)

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

计算所有 z 值的总和 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_Summation1and calc_Summation2?

谁能告诉我,什么是错的都calc_Summation1calc_Summation2

采纳答案by Jaime

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:

如果要使用 numpy 对计算进行矢量化,则需要使用 numpy 的 ufunc。此外,通常的计算方法是:

import numpy as np

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

although you can keep your approach using np.dotif you call np.expinstead of math.exp:

虽然你可以保持你的方法,np.dot如果你打电话np.exp而不是math.exp

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

It does run faster with dot:

使用 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

回答by rhombidodecahedron

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)

回答by Salix alba

k=1
def myfun(z_i):
    return z_i**k * math.exp(-z_i**2 / 2)
sum(map(myfun,z))

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

我们为要求和的事物定义一个函数,使用该map函数将其应用于列表中的每个值,然后对所有这些值求和。不得不使用外部变量k有点麻烦。

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

并使用 lambda 表达式对其进行评估

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