gpt4 book ai didi

optimization - 优化 Mathematica 的主循环

转载 作者:行者123 更新时间:2023-12-03 16:51:23 26 4
gpt4 key购买 nike

你好,

阅读此 thread关于 Mathematica 中模式匹配和函数的性能,我对 Timo's idea 印象深刻关于优化表达式的评估:

I have on occasion constructed a Dispatch table of all the functions I need and manually applied it to my starting expression. This provides a significant speed increase over normal evaluation as none of Mathematica's inbuilt functions need to be parsed against my expression.

这样的 Dispatch 表究竟应该如何构建?在哪些情况下会推荐这种方法?它是如何工作的?是否有其他优化主循环的方法?

最佳答案

为此,首先您需要能够计算符号的依赖关系。在 Mathematica Journal 的过刊中有一个包可以做到这一点,现在在线免费。这是网址:http://www.mathematica-journal.com/issue/v6i1/ .请参阅文章“Power Programming:依赖性分析”。

这是一个有效的例子:

In[1]:= <<"/path/to/DEPEND.MA"

In[2]:= $ContextPath

Out[2]= {DependencyAnalysis`,PacletManager`,WebServices`,System`,Global`}

In[3]:= f[x_]:=x x

In[4]:= g[x_]:=x+1

In[5]:= h[x_]:=f[x]+g[x]

In[6]:= i[x_]:=f[g[x]]

In[7]:= DependsOn[g][[2]]

Out[7]= {Blank,Pattern,Plus,x}

In[8]:= DownValues@@@DependsOn[g][[2]]

Out[8]= {{},{},{},{}}

In[9]:= getDownValues[s_Symbol]:=DownValues[s]

In[10]:= getDownValues[s_HoldForm]:=getDownValues@@s

In[11]:= getDownValues[s_]:={}

In[12]:= hasDownValues[x_]:=getDownValues[x]=!={}

In[13]:= ruleListEntries[x_List]:=Union[Union@@ruleListEntries/@x,{x}]

In[14]:= ruleListEntries[x_]:=Select[Union[DependsOn[x][[2]],{x}],hasDownValues]

In[15]:= ruleListEntries[f]

Out[15]= {f}

In[16]:= ruleListEntries[g]

Out[16]= {g}

In[17]:= ruleListEntries[h]

Out[17]= {h,f,g}

In[18]:= ruleListEntries[i]

Out[18]= {i,f,g}

In[19]:= dispatch=getDownValues/@ruleListEntries[i]//Flatten//Union//Dispatch

Out[19]= {HoldPattern[f[x_]]:>x x,HoldPattern[g[x_]]:>x+1,HoldPattern[i[x_]]:>f[g[x]]}

In[20]:= i[x]

Out[20]= (1+x)^2

In[21]:= HoldForm[i[x]]//.dispatch

Out[21]= (x+1) (x+1)

我看不到获取内置符号的 DownValues 的方法,因此这仅对将表达式减少到仅包含内置符号的点有用。

关于optimization - 优化 Mathematica 的主循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5296104/

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