在 Mathematica 中约束内置函数输出的最简单方法是什么?说 let Sin 只返回奇数? [英] What is the simplest way to constraint a built-in function's output in Mathematica? say let Sin returns only odd numbers?

查看:18
本文介绍了在 Mathematica 中约束内置函数输出的最简单方法是什么?说 let Sin 只返回奇数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如对于Mathematica中的一个内置函数,f,原本f[1]给出{1,2,3},但是我想让Mathematica只给出{1,3}.需要一种重写 f 的简单方法.我不想定义一个新函数或完全重写 f 或只是处理原始 f 的输出.我想重写f.

For example, for a built-in function in Mathematica, f, originally f[1] gives {1,2,3}, but I want to let Mathematica gives only {1,3}. A simple method for rewritting f is desired. I don't want to define a new function or totally rewrite f or just dealing with original f's outputs. I want to rewite f.

谢谢.:)

推荐答案

您可以使用 Villegas-Gayley 技巧为此.

对于 Sin 函数:

Unprotect[Sin];
Sin[args___]/;!TrueQ[$insideSin]:=
   Block[{$insideSin=True,result},
      If[OddQ[result=Sin[args]],result]
   ];
Protect[Sin];
{Sin[Pi],Sin[Pi/2]}

==> {Null,1}

这篇关于在 Mathematica 中约束内置函数输出的最简单方法是什么?说 let Sin 只返回奇数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆