python - 如何计算列表中的函数?

标签 python

我正在阅读“A Primer on Scientific Programming with Python”一书,但我被困在练习 2.26 上。据说写了一个函数maxmin(f, a, b, n=1000),它返回一个数学函数f(x)(在n点求值)在a和b之间的区间内的最大值和最小值。

maxmin 函数可以计算一组 n 个坐标之间的 和 b 存储在列表 x 中,然后在 x 中的点计算 f 并存储 另一个列表 y 中的值。 Python 函数 max(y) 和 min(y) 分别返回列表 y 中的最大值和最小值。

作为测试,据说

from math import cos, pi
print maxmin(cos, -pi/2, 2*pi)

应该写出(1.0, -1.0)

这是我试过的,但它没有返回任何东西!

from math import cos, pi

def maxmin(f, a, b, n=1000):
    x = [f(i) for i in range(a, b, n)]
    #print x
    maximum = max(x)
    minimum = min(x)
    return maximum, minimum

print maxmin(cos, -pi/2, 2*pi)

最佳答案

您的代码错误地使用了 range()。该函数不支持浮点参数,最后一个参数与您想象的不一样。

如果我没记错的话,您正在阅读的这本书是基于 NumPy 的。如果是这种情况,您可以简单地将 range() 替换为 numpy.linspace() .

关于python - 如何计算列表中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24355290/

相关文章:

python gensim : indices array has non-integer dtype (float64)

python - 在 Python 中使用 struct timeval

python 比较 CSV 并找出差异

python - 为什么 scipy 稀疏矩阵内存使用对矩阵中元素的数量无动于衷?

python - 托管中型 Python/Django 应用程序

python - 导入错误: No module named netsnmp

python - 从 VBA 调用 Python (Winwrap)

Python 3 套接字编程 : using sendall vs. sendto

python - 尝试使用 PIL 保存图像时出现 IndexError

python - 如何将属性方法用作查询中的字段?