Message Boards Message Boards

GROUPS:

Test for reals and integers in expression?

Posted 9 months ago
741 Views
|
5 Replies
|
3 Total Likes
|

To test that a numerical expression (typically a list of numbers) contains only reals, I wrote this function

ReV[expr_]:=VectorQ[expr,NumericalQ[#]&&(Head[#]===Real)&

Works fine. How do I extend this to test for the presence of only reals and integers? Changing the last (..) to

(Head[#]===Real||Head[#]===Integer) 

doesn't work.

5 Replies

There is no such thing as NumericalQ, I think you mean NumberQ or NumericQ?

ClearAll[ReV]
ReV[expr_]:=VectorQ[expr,NumberQ[#]&&(Head[#]===Real||Head[#]===Integer)&]
ReV[{1,2,3}]
ReV[{1.0,2.0,3.0}]
ReV[{1.0,2,3,4.0}]
ReV[{a,1.0,2,3,4.0}]
ReV[{Sqrt[2],1.0,2,3,4.0}]
ReV[{1/3,1.0,2,3,4.0}]

There are useful (but undocumented) Internal` and Developer` context functions for such tasks. Take a look at Internal`RealValuedNumericQ.

VectorQ is specially optimized for most of these. For example, VectorQ[arr, Internal`RealValuedNumericQ] will immediately return True if arr is a Real or Integer packed array. It won't unpack and won't check each element.

These functions should really be documented.


The usual caveats for undocumented functions apply. If you misuse them, bad things might happen (such as kernel crash). They may not be tested to the same standards as documented functions. This is not just an empty disclaimer. I recently got bitten by a bug where VectorQ[{}, Developer`MachineIntegerQ] returned False up to Mathematica 10.4 (it's fixed in 11.0+).

My apologies, typing typos. Corrected:

ReV[expr_]:=VectorQ[expr,NumericQ[#]&&(Head[#]===Real)&]

I use it in older versions of Mathematica (4,5) as well as the latest (11) so it should work back to v4. (Sharing-code colleagues in Europe run 4 and 5)

@Carlos Felippa do you realize every time you make a post your code does not show up?

Could you please make sure you know the rules: https://wolfr.am/READ-1ST so moderators do not have to edit your every single post.

The rules explain how to format your code properly. If you do not format code, it may become corrupted and useless to other members. Please EDIT your posts and make sure code blocks start on a new paragraph and look framed and colored like this.

int = Integrate[1/(x^3 - 1), x];
Map[Framed, int, Infinity]

enter image description here

This works for me:

ReV[expr_] := 
 VectorQ[expr, ((Head[#] === Real) || (Head[#] === Integer)) &]

I recommend that you use parens when doing logicals because the order of precedence will sometimes cause unintended results.

Regards

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