Message Boards Message Boards

1
|
3738 Views
|
4 Replies
|
2 Total Likes
View groups...
Share
Share this post:

Creating a function with default real arguments

I would like to create a function that takes a numerical value and has a default value. For instance, I can define

f[x_:10] := 2 * x

And this works. If I would like to check whether the x is a numeric value, I can write this as

f[x_?NumericQ]  = 2 * x

But if I try to do both, that is check whether it is numeric and it has default value, the function does not work. In other words, the following expression is not correct

f[x_?NumericQ:10] := 2 * x 

What should be the correct syntax in such case?

POSTED BY: Tarkeshwar Singh
4 Replies
Posted 4 years ago

This should work:

f[x:_?NumericQ:10] := 2 * x
POSTED BY: David K

What exactly do you mean? Shall f yield 2x if x is a number and 10 else? In this case you could use

Clear[f]
f[x_] := If[NumericQ[x], 2 x, 10]
f[3]
f[a]

With my system of Mma (version 7) David's code doesn't work

Clear[f]
f[x : _?NumericQ : 10] := 2*x
f[3]
f[a]
POSTED BY: Hans Dolhaine
Posted 4 years ago

Hi Hans,

Tarkeshwar is looking for a way to specify that the argument is numeric and that it has a default value if no value is passed. David's answer does that.

ClearAll@f
f[x:_?NumericQ:10] := 2 * x

f[3]
(* 6 *)

f[a]
(* f[a] *)

f[]
(* 20 *)

Does this not work in V7?

POSTED BY: Rohit Namjoshi

Hello Rohit,

it doesn't work indeed in V7

In[1]:= ClearAll@f
f[x : _?NumericQ : 10] := 2*x

f[3]
(*6*)

f[a]
(*f[a]*)

f[]

Out[3]= f[3]

Out[4]= f[a]

Out[5]= f[]
POSTED BY: Hans Dolhaine
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract