4
$\begingroup$

I'm trying to define a function accepting only real values like this:

f[x_Real] := x^2
f[0]

But it outputs

f[0]

and doesn't output 0.

Is there any reason why f[x_Real] doesn't work? I tested f[x_Integer] and f[x_Complex] and they both seem to work.

$\endgroup$
  • $\begingroup$ More convenient approach would be f[x_] /; x \[Element] Reals := x^2 or f[x_] /; Im[x] == 0 := x^2 $\endgroup$ – Artes Jul 2 at 11:20
  • $\begingroup$ That works, thank you! $\endgroup$ – bluemystic Jul 2 at 11:29
  • 1
    $\begingroup$ f[x_?NumericQ] is also good to keep in mind, though that will also allow complex numbers. $\endgroup$ – Sjoerd Smit Jul 2 at 13:09
8
$\begingroup$

Let me explain what went wrong.

When you define a function f[pattern] := ... then this will check at every occurrence of f[x] if x matches pattern.

Your pattern was x_Real which means "match any expression whose Head is Real". In Mathematica floating point numbers have the Head Real.

In[1]:= Head[0]
Out[1]= Integer

In[2]:= Head[0.]
Out[2]= Real

However, you do not care whether or not the argument has had Real, rather you want it to be an element of the set Reals. This is what Artes suggested in the comments by using a Condition

f[x_] /; Element[x, Reals] := x^2

Alternatively you could also use a PatternTest

f[x_?Element[#, Reals]&] := x^2
| improve this answer | |
$\endgroup$
3
$\begingroup$

0 without the "." is an Integer, see

Head @ 0

(* Integer *)

but

f[0.]

delivers

0.
| improve this answer | |
$\endgroup$

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