Re: IsIntegerOrFloat
- To: mathgroup at smc.vnet.net
- Subject: [mg87051] Re: IsIntegerOrFloat
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Sun, 30 Mar 2008 01:16:49 -0500 (EST)
- Organization: The Open University, Milton Keynes, UK
- References: <fsl214$g77$1@smc.vnet.net>
carlos at colorado.edu wrote:
> I need a function
>
> IsIntegerOrFloat[expr]
>
> that returns True if expr, which is generally a flat list, contains
> only integers or floating point numbers, and False otherwise.
> Rational numbers such as 1/2 are considered symbolic for this test; so is
> \[Pi] or Sqrt[5]. Appearance of any symbol, as in 2.0*a+3.5, makes it False.
> As in previous questions, this should work on versions >=4.0.
<snip>
The following should do what you are looking for (compatible with 4.0+)
at a reasonable speed (~200,000 entries processed in about 0.5 second)
IsIntegerOrFloat[expr_] :=
Cases[expr,
x_ /; Not[Head[x] === Integer || Head[x] === Real] -> False, 1,
1] /. {False} -> False /. {} -> True
Some tests and benchmarking follows.
In[1]:= IsIntegerOrFloat[expr_] :=
Cases[expr,
x_ /; Not[Head[x] === Integer || Head[x] === Real] -> False, 1,
1] /. {False} -> False /. {} -> True
In[2]:= data = {1, 1., Pi, 1/2, 2.0*a + 3.5};
Head /@ data
IsIntegerOrFloat@data
Out[3]= {Integer, Real, Symbol, Rational, Plus}
Out[4]= False
In[5]:= data = {1, 1., N@Pi, N@1/2, 2.0*a + 3.5 /. a -> 1};
Head /@ data
IsIntegerOrFloat@data
Out[6]= {Integer, Real, Real, Real, Real}
Out[7]= True
In[8]:= tst =
Join[{a}, RandomInteger[{-1000, 1000}, {10^5}],
RandomReal[{0, 1}, {10^5}]];
IsIntegerOrFloat@tst // Timing
tst = Join[RandomInteger[{-1000, 1000}, {10^5}], {a},
RandomReal[{0, 1}, {10^5}]];
IsIntegerOrFloat@tst // Timing
tst = Join[RandomInteger[{-1000, 1000}, {10^5}],
RandomReal[{0, 1}, {10^5}], {a}];
IsIntegerOrFloat@tst // Timing
tst = Join[RandomInteger[{-1000, 1000}, {10^5}],
RandomReal[{0, 1}, {10^5}]];
IsIntegerOrFloat@tst // Timing
Out[9]= {0.003186, False}
Out[11]= {0.227702, False}
Out[13]= {0.50994, False}
Out[15]= {0.50495, True}
Regards,
--
Jean-Marc