增加功能

nic*_*ell 11 wolfram-mathematica

所以一般来说,如果你有两个函数f,g:X - > Y,并且如果在Y上定义了一些二元运算+,那么f + g的规范定义为函数x - > f(x)+ G(X).

在Mathematica中实现这个的最佳方法是什么?

f[x_] := x^2
g[x_] := 2*x
h = f + g;
h[1]
Run Code Online (Sandbox Code Playgroud)

产量

(f + g)[1]
Run Code Online (Sandbox Code Playgroud)

作为输出

当然,

H = Function[z, f[z] + g[z]];
H[1]
Run Code Online (Sandbox Code Playgroud)

收益率为3.

Mr.*_*ard 12

考虑:

In[1]:= Through[(f + g)[1]]

Out[1]= f[1] + g[1]
Run Code Online (Sandbox Code Playgroud)

详细说明,您可以这样定义h:

h = Through[ (f + g)[#] ] &;
Run Code Online (Sandbox Code Playgroud)

如果你的函数和操作数有限,那么UpSetyoda推荐的语法肯定更清晰.但是,Through更一般.没有任何涉及的新定义,Times或者h可以很容易地做到:

i = Through[ (h * f * g)[#] ] &
i[7]
Run Code Online (Sandbox Code Playgroud)
43218

  • @nmaxwell,根据你对*Mathematica*的熟悉程度,你可能会发现这个信息:`combine [{__ funcs},_ operator]:=通过[operator [funcs] [#]]&` - 你可以像`h一样使用它=结合[{f,g},加号]`. (3认同)

abc*_*bcd 9

做你正在尝试做的另一种方法是使用UpSetDelayed.

f[x_] := x^2;
g[x_] := 2*x;

f + g ^:= f[#] + g[#] &; (*define upvalues for the operation f+g*)

h[x_] = f + g;

h[z]

Out[1]= 2 z + z^2
Run Code Online (Sandbox Code Playgroud)

还可以通过rcollyer(以及Leonid和Verbeia的那些)看到这个非常好的答案,了解更多关于UpValues何时使用它们的信息.