0
$\begingroup$

I have a function $f:[-1,1]\to\Bbb R$ defined by

$$f(x):=\begin{cases}\frac1{n+2},&x\in\left[-\frac1n,-\frac1{n+1}\right)\cup\left(\frac1{n+1},\frac1n\right]\\0,&\text{otherwise}\end{cases}\quad \forall n\in\Bbb N$$

and I dont have a clue about how to define it in mathematica. I was searching in the language documentation and I found the function 'Piecewise' but I dont know if this can work with such a function as the above.

Some help will be appreciated, thank you.

$\endgroup$
  • 1
    $\begingroup$ isn't it just f[x_] := 1/(Floor[Abs[1/x]] + 2) $\endgroup$ – george2079 Feb 7 '17 at 22:35
  • 1
    $\begingroup$ suppose x=.21 for example, then 1/5<x<=1/4 so n=4 and the result is 1/6 no? $\endgroup$ – george2079 Feb 7 '17 at 22:43
  • $\begingroup$ @george2079 oh, I see... I will check it. Sorry, I didnt read correctly the first time. $\endgroup$ – Masacroso Feb 7 '17 at 22:47
3
$\begingroup$

If you want something resembling your mathematical notation you need to do this:

f[x_] := Module[{
   res = FindInstance[ ( 
       1/(n + 1) < x <= 1/(n) ||  -1/n <= x < -1/(n + 1)  ) && n > 0, 
     n , Integers]
   },
  If[res == {}, 0, 1/(n + 2) /. First@res]]

It is very slow, but Perhaps useful for more complicated cases.

$\endgroup$
  • $\begingroup$ Thank you very much. I will use surely for future setups. $\endgroup$ – Masacroso Feb 7 '17 at 23:04
1
$\begingroup$
f[x_, n_Integer] := 
  If[(-1/n <= x < -1/(n + 1)) || (1/n < x <= 1/(n + 1)), 
   Evaluate[1/(n + 2)], 0];
$\endgroup$
  • $\begingroup$ Sorry but the function you are trying to represent is undefined, because $n$ is not defined, but in my function $n$ is defined as any natural number. $\endgroup$ – Masacroso Feb 7 '17 at 22:38
  • $\begingroup$ Ooopss... a simple slip, easily corrected in the answer. $\endgroup$ – David G. Stork Feb 7 '17 at 23:10
1
$\begingroup$
fun[x_] := 1/(Floor[1/Abs[x]] + 2)
fun[x_] := 0 /; Abs[x] > 1
Plot[fun[x], {x, -1, 1}, Exclusions -> None, Frame -> True,
 GridLines -> {1/# & /@ Range[-10, -1]~Join~Range[10], None}]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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