2

I want to define a function f(x) which:

  • $f(x)=x^3 +10x+ 5$ if $f(x) >0$

  • $f(x)=Undefined$ if $f(x) <0$

I have a idea:

f = Function[x, ConditionalExpression[x^3 +10x+ 5, x^3 +10x+ 5 > 0]]

but if $f(x)$ is a complicated and long expression, then the code is very long. Any one have another idea?

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
user13432
  • 51
  • 1
  • Do you want the returned value to the symbol Undefined, the string "undefined", or the standard unevaluated expression? Also, I think if $f(x)$ is a long expression, the code will probably have to be at least as long. – Michael E2 Apr 04 '14 at 10:41

2 Answers2

4

In addition to Kuba's answer:

f4[x_] := Block[{val = (x^3 + 10 x - 5)}, val /; val >= 0]

f4 will return unevaluated if the condition is not fulfilled. If it is desirable to get some value returned instead, it is convenient to define it as Indeterminate or Undefined by adding second definition:

f4[_] = Undefined

Now for f[1] you get 6 and for f[0] you get Undefined.

Alexey Popkov
  • 61,809
  • 7
  • 149
  • 368
3

There are many ways:

f1[x_?NumericQ] := (x^3 + 10 x - 5) /. n_?Negative -> "undefined"

or more safe:

f2[x_] :=  With[{val = (x^3 + 10 x - 5)}, If[Negative@val, "undefined", val]]

another one for open intervals:

f3[x_] := Clip[(x^3 + 10 x - 5), {0, ∞}] /. (0 -> "undefined")
Kuba
  • 136,707
  • 13
  • 279
  • 740
  • 1
    You can use Clips third argument to avoid the replacement and (probably) speed this up somewhat seriously, see e.g. Clip[{0, 1, 2, 3, 4}, {1, 3}, {low, high}] – Yves Klett Apr 04 '14 at 12:02
  • @YvesKlett oh of course, what was I thinking about? :) Thanks. – Kuba Apr 04 '14 at 17:24