14
$\begingroup$

I want to define an operator $G$ such that

$$G(f):=\begin{cases}f(\{x\}),&\lfloor x\rfloor\text{ is even}\\\frac1{f(\{x\})},&\lfloor x\rfloor\text{ is odd}\end{cases}$$

for any function $f$, where $\{x\}$ means "fractional part of $x$". I dont have a clue about how to do this. I wanted to write something like

G[2 + Sin[x]]

that define the above over the function $f(x)=2+\sin x$.

$\endgroup$

2 Answers 2

18
$\begingroup$
g[f_][x_?NumericQ] := If[EvenQ@Floor[x], f@FractionalPart[x], 1/f@FractionalPart[x]]

The ?NumericQ part is important because EvenQ returns False immediately for anything that is not a number.

In this case, f needs to be an actual function. Sin[x] and Sin[x]+2 are not functions. They are expressions in terms of x. Sin and Sin[#]+2& are functions. Look up Function to see what # and & mean.

Example:

g[Sin][5/2]
(* Sin[1/2] *)
$\endgroup$
2
  • $\begingroup$ I know how to build pure functions. Thank you very much. $\endgroup$
    – Masacroso
    May 10, 2017 at 13:32
  • $\begingroup$ @Masacroso Great! I was not sure, so I mentioned it just in case. In your post you show an expression like 2+Sin[x] instead of a function. If you have an expression like that, normally you also need to specify the variable, x. That's how Plot, Integrate, etc. work. $\endgroup$
    – Szabolcs
    May 10, 2017 at 13:48
5
$\begingroup$

As an alternative to Szabolcs' answer I would sugest a different approach, that quite literally follows the mathematical definition of $G(f)$. Note that we may avoid the premature evaluation of any argument that is not numeric by using Divisible instead of EvenQ or OddQ:

g[ f_Function ] := Function[ x, 
    Piecewise[
        {
          {     f[ FractionalPart @ x ],       Divisible[ Floor[x], 2 ] },
          { 1 / f[ FractionalPart @ x ], Not @ Divisible[ Floor[x], 2 ] }
        },
        Indeterminate (* in all other cases *)
    ]
]

We may then use this for numeric arguments:

f = Function[ x, 2 + Sin[x] ];
h = g[f]; (* or directly g[f] @ x *)
h[ 5/2 ]

$2 + \text{Sin}[\frac{1}{2}]$

In the given form we can now also work symbolically:

h[x] // Head

Piecewise

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.