Message Boards Message Boards

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

_?NumberQ for list arguments

Yesterday I wanted to run NMinimize on a numeric function with 21 arguments and didn't want to put _?NumberQ after each argument.
I decided it was time to figure out an equivalent approach for list arguments, since the documentation doesn't tell how to do that (as far as I know).
Here's an example of what I came up with:
f[l_List /; And @@ (NumberQ /@ l)] := l.l
And here are tests showing that it only evaluates for a list with all numeric components:
f[Range[5]]
55
f[{3, a}]
f[{3, a}]
Some of you may be wondering why this is useful.  Some numeric functions, such as FindMinimum and NMinimize,
first evaluate their arguments symbolically, probably to get symbolic derivatives, etc.  However, if an
argument is a user-defined function that fails for symbolic arguments, FindMinimum and NMinimize will fail.
The documentation says to put _?NumberQ after the scalar numeric function arguments so that symbolic evaluation
will return unevaluated and the algorithm will know that the function is numeric.  As I said earlier, I haven't seen an
equivalent approach for list arguments so I came up with my own.
POSTED BY: Frank Kampas
2 Replies
A nice application of VectorQ[expr, test]
POSTED BY: Frank Kampas
I usually end up using VectorQ in this case alongside NumericQ like this: 
f[x_?(VectorQ[#, NumericQ] &)]:=
It's not actually much more elegant or readable, but it's there. 
POSTED BY: Sean Clarke
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