gpt4 book ai didi

python - Python 中的迭代函数生成

转载 作者:太空狗 更新时间:2023-10-30 00:05:30 26 4
gpt4 key购买 nike

考虑以下想法:我想生成一个函数序列f_k,对于 k = 1,...,50 并将它们存储在 Python 字典中。举个具体的例子,假设

f_k(x)  = f_{k-1}(x) * sqrt(x)

这只是一个例子,我遇到的问题比较复杂,但这对我的问题来说无关紧要。因为在我的实际问题中 f_{k-1} 非常嘈杂并且包含舍入误差,所以我不想直接从 f_{k-1 构建 f_k },而是我首先通过样条近似来近似 f_{k-1},然后根据该样条近似确定 f_k。奇怪的是,这会导致出现一条错误消息,指出超出了最大递归深度。这是代码示例:

import numpy as np
from scipy.interpolate import interp1d
n = 50 # number of functions I want to create
args = np.linspace(1,4,20) # where to evaluate for spline approximation
fdict = dict() # dictionary that stores all the functions
fdict[0] = lambda x: x**2 # the first function

# generate function f_k as follows: First, take function f_{k-1} and
# approximate it through a spline. Multiply that spline approximation
# by sqrt(x) and store this as function f_k.
for k in range(1,n+1):

spline_approx = lambda x: interp1d( args,fdict[k-1](args) )(x)
fdict[k] = lambda x: spline_approx(x) * np.sqrt(x)

print('test evalutation: ', fdict[n](3))

这会导致错误

RecursionError: maximum recursion depth exceeded

我的问题一定是特定于 Python 的。肯定跟通过interp1d插值有关系。例如。如果我更换线路

spline_approx = lambda x: interp1d( args,fdict[k-1](args) )(x)

通过 polyfit

coefs = np.polyfit(args,fdict[k-1](args),10) # polyfit coefficients
spline_approx = lambda x: np.polyval(coefs,x) # approximation of f_{k-1}

代码运行良好。我怀疑问题的出现是因为 fdict[k-1] 没有被直接评估,而只是作为引用传递。但是我该如何解决这个问题呢?

最佳答案

引发 RecursionError 的行确实是:

spline_approx = lambda x: interp1d( args,fdict[k-1](args) )(x)

这一行意味着 spline_approx 是一个函数,给定 x,返回 interp1d(args, fdict[k-1](args)x 中评估。

由于 interp1d 返回您要放入 spline_approx 中的函数,因此该行可以简化为:

spline_approx = interp1d( args,fdict[k-1](args) )

这将停止抛出 RecursionError


为什么您的原始代码会抛出 RecursionError

在原始行中,interp1d(args, fdict[k-1](args)) 求值,因为它在 lambda 内部 表达式。此评估被推迟到该 lambda 表达式的调用。

换句话说,每次从 fdict 调用函数时,所有之前的函数都必须计算 interp1d(args, fdict[k-1](args)) .问题是 args 是一个序列,所以 fdict[k-1] 被调用的次数与 args 的元素数一样多。

调用次数当然是指数级的,因为每个函数都必须对前一个函数求值 len(args) 次。这会导致 RecursionError

另一方面,新表达式会计算 interp1d(args, fdict[k-1](args))。在此评估之后,对 fdict[k] 的调用将不再触发对 fdict[k-1] 的调用。

关于python - Python 中的迭代函数生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41778916/

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