Test integerness: Difference between revisions
→{{header|Perl 6}}: factorize |
→{{header|Python}}: Updated to handle ints, floats, and complex types. |
||
Line 23: | Line 23: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
{{incomplete}} |
|||
<lang python>>>> def isint(f): |
<lang python>>>> def isint(f): |
||
return int(f) == f |
return complex(f).imag == 0 and int(complex(f).real) == complex(f).real |
||
>>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))] |
|||
>>> isint(3.14) |
|||
[True, True, True, False, False, False] |
|||
False |
|||
>>> isint(3.0) |
|||
True |
|||
>>> </lang> |
>>> </lang> |
||
Revision as of 13:05, 22 June 2014
Given a numeric, possibly complex value, test whether or not it is an integer.
To be clear, we're not talking about whether the number is stored with the specific data type for integers, but instead we want to test whether there exists an integer with the exact same value. In other words, we want to test for integerness in the mathematical sense, not as a data type.
J
<lang J>(= <.) 3.14 7</lang>
- Output:
0 1
Perl 6
<lang perl6>for pi, 1e5, 1+0i {
say .narrow ~~ Int;
}</lang>
- Output:
False True True
Python
<lang python>>>> def isint(f):
return complex(f).imag == 0 and int(complex(f).real) == complex(f).real
>>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))] [True, True, True, False, False, False] >>> </lang>
REXX
<lang rexx>/* REXX ---------------------------------------------------------------
- 20.06.2014 Walter Pachl
- zero and negative whole numbers are integers, right?
- --------------------------------------------------------------------*/
Call test_integer 3.14 Call test_integer 1.00000 Call test_integer 33 Call test_integer 999999999 Call test_integer 99999999999 Call test_integer 1e272 Call test_integer 'AA' Call test_integer '0' Call test_integer '-3' Exit test_integer: Parse Arg x Numeric Digits 1000 Select
When datatype(x)<>'NUM' Then Say x 'is not an integer (not even a number)' /*********************************************** When x=0 Then Say x 'is zero and thus not an integer' When x<0 Then Say x 'is negative and thus not an integer' ***********************************************/ Otherwise Do If datatype(x,'W') Then Say x 'is an integer' Else Say x 'isnt an integer' End End
Return </lang> output
3.14 isn't an integer 33 is an integer 1.00000 is an integer 999999999 is an integer 99999999999 is an integer 1E272 is an integer AA is not an integer (not even a number) 0 is an integer -3 is an integer
Tcl
The simplest method of doing this is testing whether the value is equal to the value after casting it to a integral value. <lang tcl>proc isNumberIntegral {x} {
expr {$x == entier($x)}
} foreach x {3.14 7 1000000000000000000000} {
puts [format "%s: %s" $x [expr {[isNumberIntegral $x] ? "yes" : "no"}]]
}</lang>
- Output:
3.14: no 7: yes 1000000000000000000000: yes