5
$\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$
3
  • $\begingroup$ More convenient approach would be f[x_] /; x \[Element] Reals := x^2 or f[x_] /; Im[x] == 0 := x^2 $\endgroup$ Commented Jul 2, 2020 at 11:20
  • $\begingroup$ That works, thank you! $\endgroup$ Commented Jul 2, 2020 at 11:29
  • 1
    $\begingroup$ f[x_?NumericQ] is also good to keep in mind, though that will also allow complex numbers. $\endgroup$ Commented Jul 2, 2020 at 13:09

2 Answers 2

9
$\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 
$\endgroup$
1
  • $\begingroup$ f[x_?Element[#, Reals]&] := x^2 does not work , but f[x_/;Element[#, Reals]&] := x^2 works. $\endgroup$ Commented May 31, 2022 at 7:09
3
$\begingroup$

0 without the "." is an Integer, see

Head @ 0 

(* Integer *)

but

f[0.] 

delivers

0. 
$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.