Wolfram

系统教程 行业动态 更新时间:2024-06-14 17:01:34
Wolfram-Cloud / Mathematica,有效地处理递归函数(Wolfram-Cloud/Mathematica, effective working with recursive functions)

我正在使用Чебышёв-polynomials,递归定义的多项式。 对于极有可能的情况,你以前从未见过它们:

f[0,x_] := 1; f[1,x_] := x; f[n_,x_] := 2 * x * f[n-1, x] - f[n-2, x]; Plot[{f[9, x],f[3, x]},{x, -1, 1}]

我发现自己在问,因为我经常使用python,如果有一种方法可以在wolfram-cloud中构建一系列函数,那么就可以简化这个过程。

因此,我必须只计算一次f[n]一次,这样我可以相当多地改善运行时间,并允许我扩展n的范围。

I am working with Чебышёв-polynomials at the moment, recursive defined polynomials. For the very likely case you never saw them before:

f[0,x_] := 1; f[1,x_] := x; f[n_,x_] := 2 * x * f[n-1, x] - f[n-2, x]; Plot[{f[9, x],f[3, x]},{x, -1, 1}]

And I found myself asking, since I usually work with python, if there is a way to build an array of functions in wolfram-cloud, to ease the process.

Thus I have to calculate every f[n] only once, allowing me to improve the run-time quite a bit and also allowing me to extend the range of n.

最满意答案

使用memoization 。

在这种情况下,memoization比平常更棘手,因为我们使用函数,而不是函数值。

Clear[cheb] cheb[0] = 1 &; cheb[1] = # &; cheb[n_] := cheb[n] = Evaluate@Expand[2 # cheb[n - 1][#] - cheb[n - 2][#]] &

Evaluate确保在提供和参数之前对Function的内部进行评估。

Use memoization.

In this case memoization is trickier than usual because we work with functions, not function values.

Clear[cheb] cheb[0] = 1 &; cheb[1] = # &; cheb[n_] := cheb[n] = Evaluate@Expand[2 # cheb[n - 1][#] - cheb[n - 2][#]] &

The Evaluate makes sure that the insides of the Function get evaluated even before supplying and argument.

更多推荐

本文发布于:2023-04-20 18:41:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/2f8df08003f978f46d6ee5bd67424aec.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Wolfram

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!