How to define a function that commutes with D in Mathematica

﹥>﹥吖頭↗ 提交于 2019-12-05 19:31:33

Patterns are matched syntactically, not semantically. For built-in functions, if you redefine them, and if your patterns are not matched, built-in rules (definitions) are used. To see whether or not the pattern will match or why it did not match, FullForm is often useful. In this way, we see:

In[26]:= FullForm[HoldForm[D[f[Sin[x]]+1,x]]]
Out[26]//FullForm= HoldForm[D[Plus[f[Sin[x]],1],x]]

Your definition is only effective when you have f[_] inside D, while here you have D[Plus[f[..],1],x]. Thus, your definition does not match, and then the built-in is used. Here is one way to extend it to cover this case:

Unprotect[D];
D[f[y___], x_] := f[D[y, x]];
D[HoldPattern[Plus[left___, a_f, right___]], x_] := 
    D[Plus[left], x] + D[a, x] + D[Plus[right], x];
Protect[D];

Now it will work as expected. Note however that IMO redefining built-in functions such as D in this manner is a poor practice and should be avoided. For one thing, the above solution is probably not robust either, and you may find yourself adding many more rules to make it work in all cases. Also, generally, it is better to avoid redefining built-in functions if you can (one reason is that doing so may result in some very subtle bugs, since some other system functions may use the one that you redefined, and you have no control over it). I'd instead implement my own differentiation function. This is not integration, it is relatively straightforward to do and you don't put any other system's functionality in danger.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!