Help with function accepting real values
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
0 without the "." is an Integer, see
Head @ 0
(* Integer *)
but
f[0.]
delivers
0.