gpt4 book ai didi

python - 在动态大小的 Python 中创建 lambda 列表,但它们彼此完全相同

转载 作者:行者123 更新时间:2023-11-28 18:19:30 25 4
gpt4 key购买 nike

所以我试图根据要包含的项数动态生成反正切(反正切)的泰勒级数展开式。函数 arctan(x) = x - (x^3)/3 + (x^5)/5 - ...

我的代码如下:

terms = [lambda a: pow(-1.0, i) * pow(a, 1.0 + 2.0 * i) /(1.0 + 2.0 * i) \
for i in range(term_num)]

我也尝试过使用 for 循环来制定条款:

terms = []
for i in range(term_num): terms.append(lambda a: \
pow(-1.0, i) * pow(a, 1.0 + 2.0 * i) /(1.0 + 2.0 * i))

但是,当我运行的时候

for term in terms: print(term, term(x))

我得到以下输出(对于 x = 0.2,term_num = 5:

<function arctan.<locals>.<lambda> at 0x10e48f730> 5.68888888889e-08
<function arctan.<locals>.<lambda> at 0x5609e5bf8> 5.68888888889e-08
<function arctan.<locals>.<lambda> at 0x55f4c5048> 5.68888888889e-08
<function arctan.<locals>.<lambda> at 0x5609eee18> 5.68888888889e-08
<function arctan.<locals>.<lambda> at 0x5609fb598> 5.68888888889e-08

对于 x = 1/239,term_num = 6

<function arctan.<locals>.<lambda> at 0x560a7cc80> -6.255044509921559e-28
<function arctan.<locals>.<lambda> at 0x5608642f0> -6.255044509921559e-28
<function arctan.<locals>.<lambda> at 0x560a3af28> -6.255044509921559e-28
<function arctan.<locals>.<lambda> at 0x10b07fa60> -6.255044509921559e-28
<function arctan.<locals>.<lambda> at 0x560818400> -6.255044509921559e-28
<function arctan.<locals>.<lambda> at 0x55fa97378> -6.255044509921559e-28

这些总是应该在扩展中给出的最后一个值,但出于某种原因,对于所有术语。

对于 term_num 和 x 的其他值也会发生这种情况。我什至尝试过深度复制 i 因为我担心 i 在 lambda 中以某种方式被用作引用,但它不会改变输出。将 i 转换为 float 也不会改变计算。

我做错了什么?看来我成功地生成了不同的 lambda(通过引用),但出于某种原因,它们的内容都是相同的,由最后一项应该是什么决定。

最佳答案

这是由于 Python 在闭包中绑定(bind)变量的方式。来自 Common Gotchas :

Python’s closures are late binding. This means that the values of variables used in closures are looked up at the time the inner function is called.

Here, whenever any of the returned functions are called, the value of i is looked up in the surrounding scope at call time. By then, the loop has completed and i is left with its final value of 4.

(其中 i 指的是该页面上的示例,但同样适用于您的情况。)

我喜欢他们建议的使用 functools.partial 的解决方法:

from functools import partial
from operator import mul

def create_multipliers():
return [partial(mul, i) for i in range(5)]

在您的情况下,您可以编写一个辅助函数,然后部分应用它:

def term(i, a):
return pow(-1.0, i) * pow(a, 1.0 + 2.0 * i) / (1.0 + 2.0 * i)

terms = [partial(term, i) for i in range(term_num)]

关于python - 在动态大小的 Python 中创建 lambda 列表,但它们彼此完全相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46080582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com