Message Boards Message Boards

Test for reals and integers in expression?


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


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


doesn't work.

POSTED BY: Carlos Felippa
6 months ago

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

POSTED BY: Sander Huisman
6 months ago

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+).

POSTED BY: Szabolcs Horvát
6 months ago

My apologies, typing typos. Corrected:


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)

POSTED BY: Carlos Felippa
6 months ago

@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: 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

POSTED BY: Moderation Team
6 months ago

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.


POSTED BY: Neil Singer
6 months ago

Group Abstract Group Abstract