# Help with function accepting real values [closed]

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.

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

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

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


0 without the "." is an Integer, see

Head @ 0


(* Integer *)

but

f[0.]


delivers

0.