Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the simplest way to constraint a built-in function's output in Mathematica? say let Sin returns only odd numbers?

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.

Thanks. :)

like image 756
FreshApple Avatar asked May 20 '11 14:05

FreshApple


1 Answers

You can use the Villegas-Gayley trick for this.

For the Sin function:

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}
like image 144
Alexey Popkov Avatar answered Sep 28 '22 12:09

Alexey Popkov