Test integerness: Difference between revisions

Added Easylang
(Added Easylang)
 
(35 intermediate revisions by 20 users not shown)
Line 112:
 
<hr>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F isint(f)
R Complex(f).imag == 0 & fract(Complex(f).real) == 0
 
print([Complex(1.0), 2, (3.0 + 0.0i), 4.1, (3 + 4i), (5.6 + 0i)].map(f -> isint(f)))
print(isint(25.000000))
print(isint(24.999999))
print(isint(25.000100))
print(isint(-5e-2))
print(isint(Float.infinity))
print(isint(5.0 + 0.0i))
print(isint(5 - 5i))</syntaxhighlight>
 
{{out}}
<pre>
[1B, 1B, 1B, 0B, 0B, 0B]
1B
0B
0B
0B
0B
1B
0B
</pre>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
Uses LONG LONG values which in Algol 68 have a programmer specifiable number of digits. As with the C version, we need only handle the complex case directly, as Algol 68 will automatically coerce integer and real values to complex as required.
<langsyntaxhighlight lang="algol68"># set the required precision of LONG LONG values using #
# "PR precision n PR" if required #
PR precision 24 PR
Line 141 ⟶ 168:
test is int( 4.0 I 0 );
test is int( 123456789012345678901234 )
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 150 ⟶ 177:
+1.2345678901234567890123400000000000e +23_+0.0000000000000000000000000000000000e +0 is integral
</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f TEST_INTEGERNESS.AWK
BEGIN {
n = split("25.000000,24.999999,25.000100,-2.1e120,-5e-2,NaN,Inf,-0.05",arr,",")
for (i=1; i<=n; i++) {
s = arr[i]
x = (s == int(s)) ? 1 : 0
printf("%d %s\n",x,s)
}
exit(0)
}
</syntaxhighlight>
{{out}}
<pre>
1 25.000000
0 24.999999
0 25.000100
1 -2.1e120
0 -5e-2
0 NaN
0 Inf
0 -0.05
</pre>
 
=={{header|BQN}}==
<syntaxhighlight lang="bqn">IsInt ← ⊢(0=|˜)⍟⊢1=•Type
 
IsInt¨⊸≍˘ ⟨+, 0, ∞, ⊘, ¯∞, 'q', ¯42, ∞-∞, "BQN", 1e¯300, 9e15, π⟩</syntaxhighlight>
{{out}}
<pre>┌─
╵ 0 +
1 0
0 ∞
0 ⊘
0 ¯∞
0 'q'
1 ¯42
0 NaN
0 "BQN"
0 1e¯300
1 9000000000000000
0 3.141592653589793
┘</pre>
 
=={{header|C}}==
The main function that checks a numeric value is actually quite short. Because of C's weak types and implicit casting we can get away with making a function which checks long double complex types only.
 
<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
#include <complex.h>
Line 212 ⟶ 284:
printf("Test 4 (0+1.2i) = %s\n", isint(test4) ? "true" : "false");
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 237 ⟶ 309:
</pre>
 
=={{header|C++ sharp|C#}}==
<lang cpp>
#include <complex>
#include <math.h>
#include <iostream>
 
template<class Type>
struct Precision
{
public:
static Type GetEps()
{
return eps;
}
 
Length and precision of entered numbers in this solution,
static void SetEps(Type e)
are limited by the limitations of variables type of [https://en.wikipedia.org/wiki/Double-precision_floating-point_format Double].
{
eps = e;
}
 
private:
static Type eps;
};
 
<syntaxhighlight lang="c sharp">
template<class Type> Type Precision<Type>::eps = static_cast<Type>(1E-7);
 
template<class DigType>
bool IsDoubleEqual(DigType d1, DigType d2)
{
return (fabs(d1 - d2) < Precision<DigType>::GetEps());
}
 
template<class DigType>
DigType IntegerPart(DigType value)
{
return (value > 0) ? floor(value) : ceil(value);
}
 
template<class DigType>
DigType FractionPart(DigType value)
{
return fabs(IntegerPart<DigType>(value) - value);
}
 
template<class Type>
bool IsInteger(const Type& value)
{
return false;
}
 
#define GEN_CHECK_INTEGER(type) \
template<> \
bool IsInteger<type>(const type& value) \
{ \
return true; \
}
 
#define GEN_CHECK_CMPL_INTEGER(type) \
template<> \
bool IsInteger<std::complex<type> >(const std::complex<type>& value) \
{ \
type zero = type(); \
return value.imag() == zero; \
}
 
#define GEN_CHECK_REAL(type) \
template<> \
bool IsInteger<type>(const type& value) \
{ \
type zero = type(); \
return IsDoubleEqual<type>(FractionPart<type>(value), zero); \
}
 
#define GEN_CHECK_CMPL_REAL(type) \
template<> \
bool IsInteger<std::complex<type> >(const std::complex<type>& value) \
{ \
type zero = type(); \
return IsDoubleEqual<type>(value.imag(), zero); \
}
 
#define GEN_INTEGER(type) \
GEN_CHECK_INTEGER(type) \
GEN_CHECK_CMPL_INTEGER(type)
 
#define GEN_REAL(type) \
GEN_CHECK_REAL(type) \
GEN_CHECK_CMPL_REAL(type)
 
 
GEN_INTEGER(char)
GEN_INTEGER(unsigned char)
GEN_INTEGER(short)
GEN_INTEGER(unsigned short)
GEN_INTEGER(int)
GEN_INTEGER(unsigned int)
GEN_INTEGER(long)
GEN_INTEGER(unsigned long)
GEN_INTEGER(long long)
GEN_INTEGER(unsigned long long)
 
GEN_REAL(float)
GEN_REAL(double)
GEN_REAL(long double)
 
template<class Type>
inline void TestValue(const Type& value)
{
std::cout << "Value: " << value << " of type: " << typeid(Type).name() << " is integer - " << std::boolalpha << IsInteger(value) << std::endl;
}
 
int main()
{
char c = -100;
unsigned char uc = 200;
short s = c;
unsigned short us = uc;
int i = s;
unsigned int ui = us;
long long ll = i;
unsigned long long ull = ui;
 
std::complex<unsigned int> ci1(2, 0);
std::complex<int> ci2(2, 4);
std::complex<int> ci3(-2, 4);
std::complex<unsigned short> cs1(2, 0);
std::complex<short> cs2(2, 4);
std::complex<short> cs3(-2, 4);
 
std::complex<double> cd1(2, 0);
std::complex<float> cf1(2, 4);
std::complex<double> cd2(-2, 4);
 
float f1 = 1.0;
float f2 = -2.0;
float f3 = -2.4f;
float f4 = 1.23e-5f;
float f5 = 1.23e-10f;
double d1 = f5;
 
TestValue(c);
TestValue(uc);
TestValue(s);
TestValue(us);
TestValue(i);
TestValue(ui);
TestValue(ll);
TestValue(ull);
 
TestValue(ci1);
TestValue(ci2);
TestValue(ci3);
TestValue(cs1);
TestValue(cs2);
TestValue(cs3);
 
TestValue(cd1);
TestValue(cd2);
TestValue(cf1);
 
TestValue(f1);
TestValue(f2);
TestValue(f3);
TestValue(f4);
TestValue(f5);
std::cout << "Set float precision: 1e-15f\n";
Precision<float>::SetEps(1e-15f);
TestValue(f5);
TestValue(d1);
return 0;
}
</lang>
 
{{out}}
<pre>
Value: Ь of type: char is integer - true
Value: ╚ of type: unsigned char is integer - true
Value: -100 of type: short is integer - true
Value: 200 of type: unsigned short is integer - true
Value: -100 of type: int is integer - true
Value: 200 of type: unsigned int is integer - true
Value: -100 of type: __int64 is integer - true
Value: 200 of type: unsigned __int64 is integer - true
Value: (2,0) of type: class std::complex<unsigned int> is integer - true
Value: (2,4) of type: class std::complex<int> is integer - false
Value: (-2,4) of type: class std::complex<int> is integer - false
Value: (2,0) of type: class std::complex<unsigned short> is integer - true
Value: (2,4) of type: class std::complex<short> is integer - false
Value: (-2,4) of type: class std::complex<short> is integer - false
Value: (2,0) of type: class std::complex<double> is integer - true
Value: (-2,4) of type: class std::complex<double> is integer - false
Value: (2,4) of type: class std::complex<float> is integer - false
Value: 1 of type: float is integer - true
Value: -2 of type: float is integer - true
Value: -2.4 of type: float is integer - false
Value: 1.23e-05 of type: float is integer - false
Value: 1.23e-10 of type: float is integer - true
Set float precision: 1e-15f
Value: 1.23e-10 of type: float is integer - false
Value: 1.23e-10 of type: double is integer - true
</pre>
 
=={{header|C#}}==
<lang c sharp>
namespace Test_integerness
{
Line 570 ⟶ 446:
}
 
</syntaxhighlight>
</lang>
{{out| Program Input and Output :}}
<pre>
Line 654 ⟶ 530:
Another test < Y /N > . . .
 
</pre>
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">
#include <complex>
#include <math.h>
#include <iostream>
 
template<class Type>
struct Precision
{
public:
static Type GetEps()
{
return eps;
}
 
static void SetEps(Type e)
{
eps = e;
}
 
private:
static Type eps;
};
 
template<class Type> Type Precision<Type>::eps = static_cast<Type>(1E-7);
 
template<class DigType>
bool IsDoubleEqual(DigType d1, DigType d2)
{
return (fabs(d1 - d2) < Precision<DigType>::GetEps());
}
 
template<class DigType>
DigType IntegerPart(DigType value)
{
return (value > 0) ? floor(value) : ceil(value);
}
 
template<class DigType>
DigType FractionPart(DigType value)
{
return fabs(IntegerPart<DigType>(value) - value);
}
 
template<class Type>
bool IsInteger(const Type& value)
{
return false;
}
 
#define GEN_CHECK_INTEGER(type) \
template<> \
bool IsInteger<type>(const type& value) \
{ \
return true; \
}
 
#define GEN_CHECK_CMPL_INTEGER(type) \
template<> \
bool IsInteger<std::complex<type> >(const std::complex<type>& value) \
{ \
type zero = type(); \
return value.imag() == zero; \
}
 
#define GEN_CHECK_REAL(type) \
template<> \
bool IsInteger<type>(const type& value) \
{ \
type zero = type(); \
return IsDoubleEqual<type>(FractionPart<type>(value), zero); \
}
 
#define GEN_CHECK_CMPL_REAL(type) \
template<> \
bool IsInteger<std::complex<type> >(const std::complex<type>& value) \
{ \
type zero = type(); \
return IsDoubleEqual<type>(value.imag(), zero); \
}
 
#define GEN_INTEGER(type) \
GEN_CHECK_INTEGER(type) \
GEN_CHECK_CMPL_INTEGER(type)
 
#define GEN_REAL(type) \
GEN_CHECK_REAL(type) \
GEN_CHECK_CMPL_REAL(type)
 
 
GEN_INTEGER(char)
GEN_INTEGER(unsigned char)
GEN_INTEGER(short)
GEN_INTEGER(unsigned short)
GEN_INTEGER(int)
GEN_INTEGER(unsigned int)
GEN_INTEGER(long)
GEN_INTEGER(unsigned long)
GEN_INTEGER(long long)
GEN_INTEGER(unsigned long long)
 
GEN_REAL(float)
GEN_REAL(double)
GEN_REAL(long double)
 
template<class Type>
inline void TestValue(const Type& value)
{
std::cout << "Value: " << value << " of type: " << typeid(Type).name() << " is integer - " << std::boolalpha << IsInteger(value) << std::endl;
}
 
int main()
{
char c = -100;
unsigned char uc = 200;
short s = c;
unsigned short us = uc;
int i = s;
unsigned int ui = us;
long long ll = i;
unsigned long long ull = ui;
 
std::complex<unsigned int> ci1(2, 0);
std::complex<int> ci2(2, 4);
std::complex<int> ci3(-2, 4);
std::complex<unsigned short> cs1(2, 0);
std::complex<short> cs2(2, 4);
std::complex<short> cs3(-2, 4);
 
std::complex<double> cd1(2, 0);
std::complex<float> cf1(2, 4);
std::complex<double> cd2(-2, 4);
 
float f1 = 1.0;
float f2 = -2.0;
float f3 = -2.4f;
float f4 = 1.23e-5f;
float f5 = 1.23e-10f;
double d1 = f5;
 
TestValue(c);
TestValue(uc);
TestValue(s);
TestValue(us);
TestValue(i);
TestValue(ui);
TestValue(ll);
TestValue(ull);
 
TestValue(ci1);
TestValue(ci2);
TestValue(ci3);
TestValue(cs1);
TestValue(cs2);
TestValue(cs3);
 
TestValue(cd1);
TestValue(cd2);
TestValue(cf1);
 
TestValue(f1);
TestValue(f2);
TestValue(f3);
TestValue(f4);
TestValue(f5);
std::cout << "Set float precision: 1e-15f\n";
Precision<float>::SetEps(1e-15f);
TestValue(f5);
TestValue(d1);
return 0;
}
</syntaxhighlight>
 
{{out}}
<pre>
Value: Ь of type: char is integer - true
Value: ╚ of type: unsigned char is integer - true
Value: -100 of type: short is integer - true
Value: 200 of type: unsigned short is integer - true
Value: -100 of type: int is integer - true
Value: 200 of type: unsigned int is integer - true
Value: -100 of type: __int64 is integer - true
Value: 200 of type: unsigned __int64 is integer - true
Value: (2,0) of type: class std::complex<unsigned int> is integer - true
Value: (2,4) of type: class std::complex<int> is integer - false
Value: (-2,4) of type: class std::complex<int> is integer - false
Value: (2,0) of type: class std::complex<unsigned short> is integer - true
Value: (2,4) of type: class std::complex<short> is integer - false
Value: (-2,4) of type: class std::complex<short> is integer - false
Value: (2,0) of type: class std::complex<double> is integer - true
Value: (-2,4) of type: class std::complex<double> is integer - false
Value: (2,4) of type: class std::complex<float> is integer - false
Value: 1 of type: float is integer - true
Value: -2 of type: float is integer - true
Value: -2.4 of type: float is integer - false
Value: 1.23e-05 of type: float is integer - false
Value: 1.23e-10 of type: float is integer - true
Set float precision: 1e-15f
Value: 1.23e-10 of type: float is integer - false
Value: 1.23e-10 of type: double is integer - true
</pre>
 
=={{header|COBOL}}==
COBOL likes to work with fixed-point decimal numbers. For the sake of argument, this program tests the "integerness" of values that have up to nine digits before the decimal point and up to nine digits after. It can therefore be "tricked", as in the third of the four tests below, by computing a result that differs from an integer by less than 0.000000001; if there is any likelihood of such results arising, it would be a good idea to allow more digits of precision after the decimal point. Support for complex numbers (in a sense) is included, because the specification calls for it—but it adds little of interest.
<langsyntaxhighlight lang="cobol">IDENTIFICATION DIVISION.
PROGRAM-ID. INTEGERNESS-PROGRAM.
DATA DIVISION.
Line 692 ⟶ 770:
ELSE DISPLAY POSSIBLE-INTEGER ' IS NOT AN INTEGER.'.
COMPLEX-PARAGRAPH.
DISPLAY REAL-PART '+' IMAGINARY-PART 'i IS NOT AN INTEGER.'.</langsyntaxhighlight>
{{out}}
<pre>-000000004.000000000 IS AN INTEGER.
Line 700 ⟶ 778:
 
=={{header|D}}==
<langsyntaxhighlight Dlang="d">import std.complex;
import std.math;
import std.meta;
Line 786 ⟶ 864:
 
assert(isInteger(0.00009i, 0.0001));
}</langsyntaxhighlight>
 
{{out}}
Line 799 ⟶ 877:
Is 5+0i an integer? true
Is 5-5i an integer? false</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
 
{Complex number}
 
type TComplex = record
Real,Imagine: double;
end;
 
{Tolerance for fuzzy integer test}
 
const Tolerance = 0.00001;
 
function IsFloatInteger(R,Fuzz: extended): boolean;
{Determine if floating point number is an integer}
var F: extended;
begin
F:=Abs(Frac(R));
if IsNan(R) or IsInfinite(R) then Result:=False
else Result:=(F<=Fuzz) or ((1-F)<=Fuzz);
end;
 
 
function IsComplexInteger(C: TComplex; Fuzz: extended): boolean;
{Determine if Complex number is an integer}
begin
Result:=(C.Imagine=0) and IsFloatInteger(C.Real,Fuzz);
end;
 
function GetBooleanStr(B: boolean): string;
{Return Yes/No string depending on boolean}
begin
if B then Result:='Yes' else Result:='No';
end;
 
 
procedure DisplayFloatInteger(Memo: TMemo; R: extended);
{Display test result for single floating point number}
var S: string;
var B1,B2: boolean;
begin
B1:=IsFloatInteger(R,0);
B2:=IsFloatInteger(R,Tolerance);
Memo.Lines.Add(Format('%15.6n, Is Integer = %3S Fuzzy = %3S',[R,GetBooleanStr(B1),GetBooleanStr(B2)]));
end;
 
 
procedure DisplayComplexInteger(Memo: TMemo; C: TComplex);
{Dispaly test result for single complex number}
var S: string;
var B1,B2: boolean;
begin
B1:=IsComplexInteger(C,0);
B2:=IsComplexInteger(C,Tolerance);
Memo.Lines.Add(Format('%3.1n + %3.1ni Is Integer = %3S Fuzzy = %3S',[C.Real,C.Imagine,GetBooleanStr(B1),GetBooleanStr(B2)]));
end;
 
 
procedure TestIntegerness(Memo: TMemo);
var C: TComplex;
begin
DisplayFloatInteger(Memo,25.000000);
DisplayFloatInteger(Memo,24.999999);
DisplayFloatInteger(Memo,25.000100);
DisplayFloatInteger(Memo,-2.1e120);
DisplayFloatInteger(Memo,-5e-2);
DisplayFloatInteger(Memo,NaN);
DisplayFloatInteger(Memo,Infinity);
Memo.Lines.Add('');
 
C.Real:=5; C.Imagine:=0;
DisplayComplexInteger(Memo,C);
C.Real:=5; C.Imagine:=5;
DisplayComplexInteger(Memo,C);
end;
</syntaxhighlight>
{{out}}
<pre>
25.000000, Is Integer = Yes Fuzzy = Yes
24.999999, Is Integer = No Fuzzy = Yes
25.000100, Is Integer = No Fuzzy = No
-2.1E120, Is Integer = Yes Fuzzy = Yes
-0.050000, Is Integer = No Fuzzy = No
NAN, Is Integer = No Fuzzy = No
INF, Is Integer = No Fuzzy = No
 
5.0 + 0.0i Is Integer = Yes Fuzzy = Yes
5.0 + 5.0i Is Integer = No Fuzzy = No
 
Elapsed Time: 11.308 ms.
 
</pre>
 
 
=={{header|EasyLang}}==
<syntaxhighlight>
func isint x .
if x mod 1 = 0
return 1
.
.
num[] = [ 25.000000 24.999999 25.0001 -2.1e120 -5e-2 0 / 0 1 / 0 ]
#
numfmt 10 0
for n in num[]
write n & " -> "
if isint n = 1
print "integer"
else
print "no integer"
.
.
</syntaxhighlight>
 
{{out}}
<pre>
25 -> integer
24.9999990000 -> no integer
25.0001000000 -> no integer
-2.1e+120 -> integer
-0.0500000000 -> no integer
nan -> no integer
inf -> no integer
</pre>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Test do
def integer?(n) when n == trunc(n), do: true
def integer?(_), do: false
Line 808 ⟶ 1,015:
Enum.each([2, 2.0, 2.5, 2.000000000000001, 1.23e300, 1.0e-300, "123", '123', :"123"], fn n ->
IO.puts "#{inspect n} is integer?: #{Test.integer?(n)}"
end)</langsyntaxhighlight>
 
{{out}}
Line 822 ⟶ 1,029:
:"123" is integer?: false
</pre>
 
=={{header|Factor}}==
The <code>number=</code> word in the <code>math</code> vocabulary comes very close to encapsulating this task. It compares numbers for equality without regard for class, like <code>=</code> would. However, since <code>>integer</code> and <code>round</code> do not specialize on the <code>complex</code> class, we need to handle complex numbers specially. We use <code>>rect</code> to extract the real components of the complex number for further processing.
<syntaxhighlight lang="factor">USING: formatting io kernel math math.functions sequences ;
IN: rosetta-code.test-integerness
 
GENERIC: integral? ( n -- ? )
 
M: real integral? [ ] [ >integer ] bi number= ;
M: complex integral? >rect [ integral? ] [ 0 number= ] bi* and ;
GENERIC# fuzzy-int? 1 ( n tolerance -- ? )
 
M: real fuzzy-int? [ dup round - abs ] dip <= ;
M: complex fuzzy-int? [ >rect ] dip swapd fuzzy-int? swap 0
number= and ;
 
{
25/1
50+2/3
34/73
312459210312903/129381293812491284512951
25.000000
24.999999
25.000100
-2.1e120
-5e-2
0/0. ! NaN
1/0. ! Infinity
C{ 5.0 0.0 }
C{ 5 -5 }
C{ 5 0 }
}
"Number" "Exact int?" "Fuzzy int? (tolerance=0.00001)"
"%-41s %-11s %s\n" printf
[
[ ] [ integral? ] [ 0.00001 fuzzy-int? ] tri
"%-41u %-11u %u\n" printf
] each</syntaxhighlight>
{{out}}
<pre>
Number Exact int? Fuzzy int? (tolerance=0.00001)
25 t t
50+2/3 f f
34/73 f f
312459210312903/129381293812491284512951 f t
25.0 t t
24.999999 f t
25.0001 f f
-2.1e+120 t t
-0.05 f f
NAN: 8000000000000 f f
1/0. f f
C{ 5.0 0.0 } t t
C{ 5 -5 } f f
5 t t
</pre>
 
=={{header|Fortran}}==
===Straightforward===
Line 827 ⟶ 1,092:
 
The MODULE protocol of F90 is used, merely to save on the need to define the types of the function in each routine that uses them, since there is no default type for LOGICAL. Otherwise, this is F77 style.
<langsyntaxhighlight Fortranlang="fortran"> MODULE ZERMELO !Approach the foundations of mathematics.
CONTAINS
LOGICAL FUNCTION ISINTEGRAL(X) !A whole number?
Line 854 ⟶ 1,119:
Z = DCMPLX(-3D0,4*ATAN(1D0))
WRITE (6,*) ISINTEGRALZ(Z),Z
END</langsyntaxhighlight>
<pre>
See if some numbers are integral...
Line 865 ⟶ 1,130:
The argument is the same with binary (or base 4, 8 or 16), but, you have to know what base is used to prepare the proper boundary value, similarly you must ascertain just how many digits of precision are in use, remembering that in binary the leading one of normalised numbers may be represented implicitly, or it may be explicitly present. One would have to devise probing routines with delicate calculations that may be disrupted by various compiler optimisation tricks and unanticipated details of the arithmetic mill. For instance, the Intel 8087 floating-point co-processor and its descendants use an implicit leading-one bit for 32- and 64-bit floating-point numbers, but ''not'' for 80-bit floating-point numbers. So if your compiler offers a REAL*10 type, such variables will enjoy a slightly different style of arithmetic. Further, ''during'' a calculation (add, subtract, multiply, divide) a further three guard bits (with special meanings) are employed. Calculations are done with full 83-bit precision to yield an 80-bit result; it is only when values are stored that they are converted to single or double precision format in storage - the register retains full precision. On top of that, the arithmetic can employ "denormalised" numbers during underflow towards zero. Chapter 6 of ''The I8087 Numeric Data Processor'', page 219, remarks "At least some of the generalised numerical solutions to common mathematical procedures have coding that is so involved and tricky in order to take care of all possible roundoff contingencies that they have been termed 'pornographic algorithms'". So a probe routine that worked for one design will likely need tweaking when tried on another system.
 
To determine the number of digits of precision, one probes somewhat as follows:<langsyntaxhighlight Fortranlang="fortran"> X = 1
10 X = X*BASE
Y = X + 1
D = Y - X
IF (D .EQ. 1) GO TO 10</langsyntaxhighlight>
Or alternatively, compare 1 + ''eps'' to 1, successively dividing ''eps'' by BASE.
 
Line 881 ⟶ 1,146:
 
Despite the attempt at generality, there will be difficulties on systems whose word sizes are not multiples of eight bits so that the REAL*4 scheme falters. Still, it is preferable to a blizzard of terms such as small int, int, long int, long long int. A decimal computer would be quite different in its size specifications, and there have been rumours of a Russian computer that worked in base three...
<syntaxhighlight lang="fortran">
<lang Fortran>
MODULE ZERMELO !Approach the foundations of mathematics.
INTERFACE ISINTEGRAL !And obscure them with computerese.
Line 943 ⟶ 1,208:
WRITE (6,*) ISINTEGRAL(Z),Z
END
</syntaxhighlight>
</lang>
 
<pre>
Line 953 ⟶ 1,218:
F (-3.00000000000000,3.14159265358979)
</pre>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="vb">#define isInteger(x) iif(Int(val(x)) = val(x), 1, 0)
 
Dim As String test(1 To 8) = {"25.000000", "24.999999", "25.000100", "-2.1e120", "-5e-2", "NaN", "Inf", "-0.05"}
 
For i As Integer = 1 To Ubound(test)
Dim As String s = test(i)
Print s,
If isInteger(s) then Print "is integer" Else Print "is not integer"
Next i
 
Sleep</syntaxhighlight>
{{out}}
<pre>25.000000 is integer
24.999999 is not integer
25.000100 is not integer
-2.1e120 is integer
-5e-2 is not integer
NaN is not integer
Inf is integer
-0.05 is not integer</pre>
 
=={{header|Free Pascal}}==
<syntaxhighlight lang="delphi">// in FPC 3.2.0 the definition of `integer` still depends on the compiler mode
{$mode objFPC}
 
uses
// used for `isInfinite`, `isNan` and `fMod`
math,
// NB: `ucomplex`’s `complex` isn’t a simple data type as ISO 10206 requires
ucomplex;
 
{ --- determines whether a `float` value is (almost) an `integer` ------ }
function isInteger(x: float; const fuzziness: float = 0.0): Boolean;
// nested routine allows us to spare an `if … then` statement below
function fuzzyInteger: Boolean;
begin
// `x mod 1.0` uses `fMod` function from `math` unit
x := x mod 1.0;
result := (x <= fuzziness) or (x >= 1.0 - fuzziness);
end;
begin
{$push}
// just for emphasis: use lazy evaluation strategy (currently default)
{$boolEval off}
result := not isInfinite(x) and not isNan(x) and fuzzyInteger;
{$pop}
end;
 
{ --- check whether a `complex` number is (almost) in ℤ ---------------- }
function isInteger(const x: complex; const fuzziness: float = 0.0): Boolean;
begin
// you could use `isZero` from the `math` unit for a fuzzy zero
isInteger := (x.im = 0.0) and isInteger(x.re, fuzziness)
end;
 
{ --- test routine ----------------------------------------------------- }
procedure test(const x: float);
const
tolerance = 0.00001;
w = 42;
var
s: string;
begin
writeStr(s, 'isInteger(', x);
writeLn(s:w, ') = ', isInteger(x):5,
s:w, ', ', tolerance:7:5, ') = ', isInteger(x, tolerance):5);
end;
 
{ === MAIN ============================================================= }
begin
test(25.000000);
test(24.999999);
test(25.000100);
test(-2.1e120);
test(-5e-2);
test(NaN);
test(Infinity);
writeLn(isInteger(5.0 + 0.0 * i));
writeLn(isInteger(5 - 5 * i));
end.</syntaxhighlight>
{{out}}
<pre> isInteger( 2.50000000000000000000E+0001) = TRUE isInteger( 2.50000000000000000000E+0001, 0.00001) = TRUE
isInteger( 2.49999990000000000007E+0001) = FALSE isInteger( 2.49999990000000000007E+0001, 0.00001) = TRUE
isInteger( 2.50000999999999999994E+0001) = FALSE isInteger( 2.50000999999999999994E+0001, 0.00001) = FALSE
isInteger(-2.10000000000000000006E+0120) = TRUE isInteger(-2.10000000000000000006E+0120, 0.00001) = TRUE
isInteger(-5.00000000000000000007E-0002) = TRUE isInteger(-5.00000000000000000007E-0002, 0.00001) = TRUE
isInteger( Nan) = FALSE isInteger( Nan, 0.00001) = FALSE
isInteger( +Inf) = FALSE isInteger( +Inf, 0.00001) = FALSE
TRUE
FALSE</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,111 ⟶ 1,469:
show("12345/5")
show(new(customIntegerType))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,166 ⟶ 1,524:
 
Some imports for additional number types
<langsyntaxhighlight lang="haskell">import Data.Decimal
import Data.Ratio
import Data.Complex</langsyntaxhighlight>
 
Haskell is statically typed, so in order to get universal integerness test we define a class of numbers, which may contain integers:
<langsyntaxhighlight lang="haskell">class ContainsInteger a where
isInteger :: a -> Bool</langsyntaxhighlight>
 
Laws for this class are simple:
Line 1,186 ⟶ 1,544:
 
Integral numbers:
<langsyntaxhighlight lang="haskell">instance ContainsInteger Int where isInteger _ = True
instance ContainsInteger Integer where isInteger _ = True</langsyntaxhighlight>
 
Real fractional numbers:
<langsyntaxhighlight lang="haskell">isIntegerF :: (Eq x, RealFrac x) => x -> Bool
isIntegerF x = x == fromInteger (truncate x)
 
instance ContainsInteger Double where isInteger = isIntegerF
instance Integral i => ContainsInteger (DecimalRaw i) where isInteger = isIntegerF
instance Integral i => ContainsInteger (Ratio i) where isInteger = isIntegerF</langsyntaxhighlight>
 
Complex numbers:
<langsyntaxhighlight lang="haskell">instance (Eq a, Num a, ContainsInteger a) => ContainsInteger (Complex a) where
isInteger z = isInteger (realPart z) && (imagPart z == 0)</langsyntaxhighlight>
 
'''Extra credit'''
 
Approximate integerness for fractional numbers:
<langsyntaxhighlight lang="haskell">x ~~ eps = abs x <= eps
 
almostInteger :: RealFrac a => a -> a -> Bool
Line 1,210 ⟶ 1,568:
 
almostIntegerC :: RealFrac a => a -> Complex a -> Bool
almostIntegerC eps z = almostInteger eps (realPart z) && (imagPart z) ~~ eps</langsyntaxhighlight>
 
'''Testing'''
<langsyntaxhighlight lang="haskell">tests = all (== True)
[ isInteger (5 :: Integer)
, isInteger (5.0 :: Decimal)
Line 1,237 ⟶ 1,595:
, not $ almostInteger 0.01 2.02
, almostIntegerC 0.001 (5.999999 :+ 0.000001)
]</langsyntaxhighlight>
 
'''Possible use'''
Line 1,243 ⟶ 1,601:
Effective definition of Pithagorean triangles:
 
<langsyntaxhighlight lang="haskell">pithagoreanTriangles :: [[Integer]]
pithagoreanTriangles =
[ [a, b, round c] | b <- [1..]
, a <- [1..b]
, let c = sqrt (fromInteger (a^2 + b^2))
, isInteger (c :: Double) ]</langsyntaxhighlight>
<pre>λ> take 7 pithagoreanTriangles
[[3,4,5],[6,8,10],[5,12,13],[9,12,15],[8,15,17],[12,16,20],[15,20,25]]
Line 1,259 ⟶ 1,617:
 
=={{header|J}}==
'''Solution''':<langsyntaxhighlight lang="j"> isInt =: (= <.) *. (= {.@+.)</langsyntaxhighlight>
'''Alternative solution''' (remainder after diving by 1?): <langsyntaxhighlight lang="j"> isInt=: (0 = 1&|) *. (0 = {:@+.)</langsyntaxhighlight>
'''Example''':<langsyntaxhighlight lang="j"> isInt 3.14 7 1.4j0 4j0 5j3 5r3 6r3
0 1 0 1 0 0 1</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|Kotlin}}
<langsyntaxhighlight Javalang="java">import java.math.BigDecimal;
import java.util.List;
 
Line 1,365 ⟶ 1,723:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>25.000000 is an integer
Line 1,396 ⟶ 1,754:
we shall also identify the rational numbers p/q with JSON objects that have the form:
{"type": "rational", "p": p, "q": q}.
<langsyntaxhighlight lang="jq">def is_integral:
if type == "number" then . == floor
elif type == "array" then
Line 1,405 ⟶ 1,763:
and (.q | is_integral)
and ((.p / .q) | is_integral)
end ;</langsyntaxhighlight>
'''Example''':
<langsyntaxhighlight lang="jq">(
0, -1, [3,0], {"p": 4, "q": 2, "type": "rational"},
1.1, -1.1, [3,1], {"p": 5, "q": 2, "type": "rational"}
) | "\(.) => \(if is_integral then "integral" else "" end)"</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -r -n -f is_integral.jq
0 => integral
-1 => integral
Line 1,420 ⟶ 1,778:
-1.1 =>
[3,1] =>
{"p":5,"q":2,"type":"rational"} => </langsyntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia"># v0.6.0
 
@show isinteger(25.000000)
Line 1,434 ⟶ 1,792:
@show isinteger(complex(5.0, 0.0))
@show isinteger(complex(5, 5))
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,449 ⟶ 1,807:
=={{header|Kotlin}}==
As Kotlin doesn't have built in rational or complex number classes, we create 'bare bones' classes for the purposes of this task:
<langsyntaxhighlight lang="scala">// version 1.1.2
 
import java.math.BigInteger
Line 1,516 ⟶ 1,874:
println("$r is ${if (exact) "an" else "not an"} integer")
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,543 ⟶ 1,901:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function isInt (x) return type(x) == "number" and x == math.floor(x) end
 
print("Value\tInteger?")
print("=====\t========")
local testCases = {2, 0, -1, 3.5, "String!", true}
for _, input in pairs(testCases) do print(input, isInt(input)) end</langsyntaxhighlight>
{{out}}
<pre>Value Integer?
Line 1,558 ⟶ 1,916:
String! false
true false</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
The built-in function IntegerQ performs the required test
<syntaxhighlight lang="mathematica">IntegerQ /@ {E, 2.4, 7, 9/2}</syntaxhighlight>
{{out}}<pre>{False,False,True,False}</pre>
=={{header|Nim}}==
A taxonomy of Nim number types:
 
::– SomeInteger: integer types, signed or unsigned, 8,16,32,or 64 bits
 
::– SomeFloat: floating point, 32 or 64 bits
 
::– SomeNumber: SomeInteger or SomeFloat
 
::– Rational: rational type; a numerator and denominator, of any (identical) SomeInteger type
 
::– Complex: complex type; real and imaginary of any (identical) SomeFloat type
 
<syntaxhighlight lang="nim">import complex, rationals, math, fenv, sugar
 
func isInteger[T: Complex | Rational | SomeNumber](x: T; tolerance = 0f64): bool =
when T is Complex:
x.im == 0 and x.re.isInteger
elif T is Rational:
x.dup(reduce).den == 1
elif T is SomeFloat:
ceil(x) - x <= tolerance
elif T is SomeInteger:
true
 
# Floats.
assert not NaN.isInteger
assert not INF.isInteger # Indeed, "ceil(INF) - INF" is NaN.
assert not (-5e-2).isInteger
assert (-2.1e120).isInteger
assert 25.0.isInteger
assert not 24.999999.isInteger
assert 24.999999.isInteger(tolerance = 0.00001)
assert not (1f64 + epsilon(float64)).isInteger
assert not (1f32 - epsilon(float32)).isInteger
# Rationals.
assert not (5 // 3).isInteger
assert (9 // 3).isInteger
assert (-143 // 13).isInteger
# Unsigned integers.
assert 3u.isInteger
# Complex numbers.
assert not (1.0 + im 1.0).isInteger
assert (5.0 + im 0.0).isInteger</syntaxhighlight>
 
=={{header|ooRexx}}==
<langsyntaxhighlight lang="oorexx">/* REXX ---------------------------------------------------------------
* 22.06.2014 Walter Pachl using a complex data class
* ooRexx Distribution contains an elaborate complex class
* parts of which are used here
* see REXX for Extra Credit implementation
*--------------------------------------------------------------------*/
Numeric Digits 1000
Line 1,618 ⟶ 2,026:
::method string /* format as a string value */
expose real imaginary /* get the state info */
return real'+'imaginary'i' /* format as real+imaginaryi */</langsyntaxhighlight>
'''output'''
<pre>1E+12+0i is an integer
Line 1,640 ⟶ 2,048:
3+0i is an integer</pre>
 
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
The built-in function IntegerQ performs the required test
<lang Mathematica>IntegerQ /@ {E, 2.4, 7, 9/2}</lang>
{{out}}<pre>{False,False,True,False}</pre>
=={{header|PARI/GP}}==
 
The operator <code>==</code> does what we want here, comparing a number mathematically regardless of how it's stored. <code>===</code> checks literal equivalence instead.
 
<langsyntaxhighlight lang="parigp">isInteger(z)=real(z)==real(z)\1 && imag(z)==imag(z)\1;
apply(isInteger, [7, I, 1.7 + I, 10.0 + I, 1.0 - 7.0 * I])</langsyntaxhighlight>
{{out}}
<pre>%1 = [1, 1, 0, 1, 1]</pre>
Line 1,656 ⟶ 2,059:
=={{header|Perl}}==
 
<langsyntaxhighlight perl6lang="perl">use Math::Complex;
 
sub is_int {
Line 1,671 ⟶ 2,074:
for (5, 4.1, sqrt(2), sqrt(4), 1.1e10, 3.0-0.0*i, 4-3*i, 5.6+0*i) {
printf "%20s is%s an integer\n", $_, (is_int($_) ? "" : " NOT");
}</langsyntaxhighlight>
 
{{out}}
Line 1,685 ⟶ 2,088:
</pre>
 
=={{header|Perl 6Pascal}}==
{{works with|Extended Pascal}}
Within Pascal’s dogma, the programmer is not supposed to be concerned about internal memory representation of specific values.
Pascal teaches you to program without making any presumptions about the underlying system.
That also means, you cannot properly inspect numeric properties beyond <tt>maxInt</tt> and <tt>maxReal</tt>.
<syntaxhighlight lang="pascal">program integerness(output);
 
{ determines whether a `complex` also fits in `integer` ---------------- }
In Perl 6, all numeric types have a method called <tt>narrow</tt>, which returns an object with the same value but of the most appropriate type. So we can just check if ''that'' object is an <tt>Int</tt>. This works even with floats with large exponents, because the <tt>Int</tt> type supports arbitrarily large integers.
function isRealIntegral(protected x: complex): Boolean;
begin
{ It constitutes an error if no value for `trunc(x)` exists, }
{ thus check re(x) is in the range -maxInt..maxInt first. }
isRealIntegral := (im(x) = 0.0) and_then
(abs(re(x)) <= maxInt * 1.0) and_then
(trunc(re(x)) * 1.0 = re(x))
end;
 
{ calls isRealIntegral with zero imaginary part ------------------------ }
<lang perl6>multi is-int ($n) { $n.narrow ~~ Int }</lang>
function isIntegral(protected x: real): Boolean;
begin
isIntegral := isRealIntegral(cmplx(x * 1.0, 0.0))
end;
 
{ Rosetta code test ---------------------------------------------------- }
For the extra credit task, we can add another multi candidate that checks the distance between the number and it's nearest integer, but then we'll have to handle complex numbers specially:
procedure test(protected x: complex);
begin
writeLn(re(x), ' + ', im(x), ' 𝒾 : ',
isIntegral(re(x)), ' ', isRealIntegral(x))
end;
{ === MAIN ============================================================= }
begin
test(cmplx(25.0, 0.0));
test(cmplx(24.999999, 0.0));
test(cmplx(25.000100, 0.0));
test(cmplx(-2.1E120, 0.0));
test(cmplx(-5E-2, 0.0));
test(cmplx(5.0, 0.0));
test(cmplx(5, -5));
end.</syntaxhighlight>
{{out}}
<pre> 2.500000000000000e+01 + 0.000000000000000e+00 𝒾 : True True
2.499999900000000e+01 + 0.000000000000000e+00 𝒾 : False False
2.500010000000000e+01 + 0.000000000000000e+00 𝒾 : False False
-2.100000000000000e+120 + 0.000000000000000e+00 𝒾 : False False
-5.000000000000000e-02 + 0.000000000000000e+00 𝒾 : False False
5.000000000000000e+00 + 0.000000000000000e+00 𝒾 : True True
5.000000000000000e+00 + -5.000000000000000e+00 𝒾 : True False</pre>
Note that the <tt>program</tt> ''fails'' on the test case <tt>-2.1E120</tt>.
The utilized <tt>trunc</tt> function only works if a truncated <tt>integer</tt> value ''does'' exist.
 
=={{header|Phix}}==
<lang perl6>multi is-int ($n, :$tolerance!) {
{{libheader|Phix/basics}}
abs($n.round - $n) <= $tolerance
In most cases the builtin works pretty well, with Phix automatically storing integer results as such.
}
multi is-int (Complex $n, :$tolerance!) {
is-int($n.re, :$tolerance) && abs($n.im) < $tolerance
}</lang>
 
<!--<syntaxhighlight lang="phix">-->
Testing:
<span style="color: #0000FF;">?</span><span style="color: #004080;">integer</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3.5</span><span style="color: #0000FF;">+</span><span style="color: #000000;">3.5</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- true</span>
<span style="color: #0000FF;">?</span><span style="color: #004080;">integer</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3.5</span><span style="color: #0000FF;">+</span><span style="color: #000000;">3.4</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- false</span>
<!--</syntaxhighlight>-->
 
The round function takes an inverted precision, so 1000000 means to the nearest 0.000001 and 100000 means the nearest 0.00001
<lang perl6>for 25.000000, 24.999999, 25.000100, -2.1e120, -5e-2, Inf, NaN, 5.0+0.0i, 5-5i {
printf "%-7s %-9s %-5s %-5s\n", .^name, $_,
is-int($_),
is-int($_, :tolerance<0.00001>);
}</lang>
 
<!--<syntaxhighlight lang="phix">-->
{{out}}
<span style="color: #0000FF;">?</span><span style="color: #004080;">integer</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">round</span><span style="color: #0000FF;">(</span><span style="color: #000000;">24.999999</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1000000</span><span style="color: #0000FF;">))</span> <span style="color: #000080;font-style:italic;">-- false</span>
<pre>
<span style="color: #0000FF;">?</span><span style="color: #004080;">integer</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">round</span><span style="color: #0000FF;">(</span><span style="color: #000000;">24.999999</span><span style="color: #0000FF;">,</span><span style="color: #000000;">100000</span><span style="color: #0000FF;">))</span> <span style="color: #000080;font-style:italic;">-- true</span>
Rat 25 True True
<!--</syntaxhighlight>-->
Rat 24.999999 False True
Rat 25.0001 False False
Num -2.1e+120 True True
Num -0.05 False False
Num Inf False False
Num NaN False False
Complex 5+0i True True
Complex 5-5i False False
</pre>
 
=={{header|Phix}}==
In most cases the builtin works prety well, with Phix automatically storing integer results as such.
<lang Phix>?integer(3.5+3.5) -- true
?integer(3.5+3.4) -- false</lang>
The round function takes an inverted precision, so 1000000 means to the nearest 0.000001 and 100000 means the nearest 0.00001
<lang Phix>?integer(round(24.999999,1000000)) -- false
?integer(round(24.999999,100000)) -- true</lang>
By default the inverted precision of round is 1, and that does exactly what you'd expect.
 
<lang Phix>?equal(-2.1e120,round(-2.1e120)) -- true
<!--<syntaxhighlight lang="phix">-->
?equal(-2.15,round(-2.15)) -- false</lang>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">equal</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">2.1e120</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">round</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">2.1e120</span><span style="color: #0000FF;">))</span> <span style="color: #000080;font-style:italic;">-- true</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">equal</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">2.15</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">round</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">2.15</span><span style="color: #0000FF;">))</span> <span style="color: #000080;font-style:italic;">-- false</span>
<!--</syntaxhighlight>-->
 
Technically though, -2.1e120 is way past precision limits, as next, so declaring it integer is deeply flawed...
It is not only way too big to fit in an integer, but also simply too big to actually have a fractional part.
Obviously using bigatoms would "solve" this, as long as I was prepared to wait for it to wade through the 120+
digits of precision needed, that is compared to the mere 19 or so that the raw physical hardware can manage.
 
<lang Phix>?equal(-2.1e120,-2.1e120+PI) -- true!!</lang>
<!--<syntaxhighlight lang="phix">-->
Phix considers both nan and inf as not an integer, and does not support complex numbers (as a primitive type). Two final examples:
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">equal</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">2.1e120</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">2.1e120</span><span style="color: #0000FF;">+</span><span style="color: #000000;">PI</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- true!!</span>
<lang Phix>?integer(-5e-2) -- false
<!--</syntaxhighlight>-->
?integer(25.000000) -- true</lang>
 
Phix considers both nan and inf as not an integer, and does not support complex numbers (as a primitive type, though there is a builtins/complex.e, not an autoinclude). Two final examples:
 
<!--<syntaxhighlight lang="phix">-->
<span style="color: #0000FF;">?</span><span style="color: #004080;">integer</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">5e-2</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- false</span>
<span style="color: #0000FF;">?</span><span style="color: #004080;">integer</span><span style="color: #0000FF;">(</span><span style="color: #000000;">25.000000</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- true</span>
<!--</syntaxhighlight>-->
 
=={{header|PicoLisp}}==
Pico Lisp scaled fixed-point numbers. Every number is stored an an Integer and a Non-integer only relative to the scale applied. For this example we assume that all numbers are generated with the same scale. This is the common case.
<syntaxhighlight lang="picolisp">
<lang PicoLisp>
(de int? (N)
(= N (* 1.0 (/ N 1.0)))) #returns T or NIL
Line 1,757 ⟶ 2,195:
(int? "RE") #-> "RE" -- Number expected
(int? (*/ 2.0 1.0 3.0)) #-> NIL # 6667 is not an integer of the scale of 4, use of */ because of the scale
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Test-Integer ($Number)
{
Line 1,781 ⟶ 2,219:
}
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
Test-Integer 9
Test-Integer 9.9
Line 1,788 ⟶ 2,226:
Test-Integer (New-Object System.Numerics.Complex(14,56))
Test-Integer "abc"
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,800 ⟶ 2,238:
=={{header|Python}}==
 
<langsyntaxhighlight lang="python">>>> def isint(f):
return complex(f).imag == 0 and complex(f).real.is_integer()
 
Line 1,826 ⟶ 2,264:
>>> isint(5-5j)
False
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
 
Quackery uses bignums ("numbers" in the Quackery nomenclature) and comes with a bignum rational ("vulgars") arithmetic library. Quackery does not differentiate between two numbers on the stack and one vulgar. <code>v-is-num</code> returns true (1) if the top two numbers on the stack can be interpreted as a vulgar with no fractional component, and false (0) otherwise.
 
<code>approxint</code> is the extra credit version. Tolerance is specified to a number of decimal places.
 
<syntaxhighlight lang="quackery"> [ $ "bigrat.qky" loadfile ] now!
[ mod not ] is v-is-num ( n/d --> b )
 
[ 1+ dip [ proper rot drop ]
10 swap ** round v-is-num ] is approxint ( n/d n --> b )</syntaxhighlight>
 
{{out}}
 
Testing in the Quackery shell.
 
<pre>/O> $ "25.000000" $->v drop v-is-num iff [ say "true" ] else [ say "false" ] cr
... $ "24.999999" $->v drop v-is-num iff [ say "true" ] else [ say "false" ] cr
... $ "25.000100" $->v drop v-is-num iff [ say "true" ] else [ say "false" ] cr
...
true
false
false
 
Stack empty.
 
/O> $ "25.000000" $->v drop 3 approxint iff [ say "true" ] else [ say "false" ] cr
... $ "24.999999" $->v drop 3 approxint iff [ say "true" ] else [ say "false" ] cr
... $ "25.000100" $->v drop 3 approxint iff [ say "true" ] else [ say "false" ] cr
...
true
true
false
 
Stack empty.</pre>
 
=={{header|Racket}}==
Line 1,835 ⟶ 2,310:
See [http://docs.racket-lang.org/reference/number-types.html?q=integer%3F#%28def._%28%28quote._~23~25kernel%29._integer~3f%29%29 documentation for <code>integer?</code>]
 
<langsyntaxhighlight lang="racket">#lang racket
(require tests/eli-tester)
 
Line 1,887 ⟶ 2,362:
(integer? pi) => #f
)
</syntaxhighlight>
</lang>
All tests pass.
 
=={{header|Raku}}==
(formerly Perl 6)
 
In Raku, all numeric types have a method called <tt>narrow</tt>, which returns an object with the same value but of the most appropriate type. So we can just check if ''that'' object is an <tt>Int</tt>. This works even with floats with large exponents, because the <tt>Int</tt> type supports arbitrarily large integers.
 
For the extra credit task, we can add another multi candidate that checks the distance between the number and it's nearest integer, but then we'll have to handle complex numbers specially.
 
<syntaxhighlight lang="raku" line>multi is-int ($n) { $n.narrow ~~ Int }
 
multi is-int ($n, :$tolerance!) {
abs($n.round - $n) <= $tolerance
}
 
multi is-int (Complex $n, :$tolerance!) {
is-int($n.re, :$tolerance) && abs($n.im) < $tolerance
}
 
# Testing:
 
for 25.000000, 24.999999, 25.000100, -2.1e120, -5e-2, Inf, NaN, 5.0+0.0i, 5-5i {
printf "%-7s %-9s %-5s %-5s\n", .^name, $_,
is-int($_),
is-int($_, :tolerance<0.00001>);
}</syntaxhighlight>
 
{{out}}
<pre>
Rat 25 True True
Rat 24.999999 False True
Rat 25.0001 False False
Num -2.1e+120 True True
Num -0.05 False False
Num Inf False False
Num NaN False False
Complex 5+0i True True
Complex 5-5i False False
</pre>
 
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 20.06.2014 Walter Pachl
* 22.06.2014 WP add complex numbers such as 13-12j etc.
Line 1,979 ⟶ 2,492:
imag=imag_sign||imag_v
 
Return real imag</langsyntaxhighlight>
'''output'''
<pre>3.14 isn't an integer
Line 2,000 ⟶ 2,513:
j is not an integer (imaginary part is not zero)
0003-00.0j is an integer</pre>
 
===version 1a Extra Credit===
<syntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* Extra credit
* Instead of using the datatype built-in function one could use this
*--------------------------------------------------------------------*/
Call testi 25.000000
Call testi 24.999999
Call testi 25.000100
Call testi 0.9999999
Call testi -0.9999999
Exit
 
testi:
Parse Arg x
If pos('.',x)>0 Then Do
xx=abs(x)
Parse Value abs(xx) With '.' d
d5=left(d,5,0)
End
Else d5=''
If d5='' | wordpos(d5,'00000 99999')>0 Then
Say x 'is an integer'
Else
Say x 'isn''t an integer'
Return</syntaxhighlight>
{{out}}
<pre>25.000000 is an integer
24.999999 is an integer
25.000100 isn't an integer
0.9999999 is an integer
-0.9999999 is an integer</pre>
 
===version 2===
Line 2,010 ⟶ 2,555:
 
Also, most REXXes have a limit on the minimum/maximum value of the power in exponentiated numbers.
<langsyntaxhighlight lang="rexx">/*REXX program tests if a number (possibly complex) is equivalent to an integer. */
numeric digits 3000 /*be able to handle gihugic integers. */
parse arg #s /*obtain optional numbers list from CL.*/
Line 2,059 ⟶ 2,604:
x= left(x, e+s) /* " " " real " " " */
if isInt(z) then if z\=0 then x=. /*Not imaginary part=0? Not an integer.*/
return /*return to the invoker of this sub. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 2,097 ⟶ 2,642:
 
would be considered an integer &nbsp; (extra blanks were added to show the number with more clarity).
<langsyntaxhighlight lang="rexx">/*REXX program tests if a number (possibly complex) is equivalent to an integer. */
numeric digits 3000 /*be able to handle gihugic integers. */
unaB= '++ -- -+ +-' /*a list of unary operators.*/
Line 2,155 ⟶ 2,700:
x= left(x, e+s) /* " " " real " " " */
if isInt(z) then if z\=0 then x=. /*Not imaginary part=0? Not an integer.*/
return /*return to the invoker of this sub. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 2,167 ⟶ 2,712:
 
Testing for integerness of floats, rationals and complex numbers:
<langsyntaxhighlight lang="ruby">
class Numeric
def to_i?
Line 2,181 ⟶ 2,726:
ar.each{|num| puts "#{num} integer? #{num.to_i?}" }
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,229 ⟶ 2,774:
sash[r7rs]> (integer? 1e120)
#t
</pre>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">func is_int (n, tolerance=0) {
!!(abs(n.real.round + n.imag - n) <= tolerance)
}
 
%w(25.000000 24.999999 25.000100 -2.1e120 -5e-2 Inf NaN 5.0+0.0i 5-5i).each {|s|
var n = Number(s)
printf("%-10s %-8s %-5s\n", s,
is_int(n),
is_int(n, tolerance: 0.00001))
}</syntaxhighlight>
{{out}}
<pre>
25.000000 true true
24.999999 false true
25.000100 false false
-2.1e120 true true
-5e-2 false false
Inf false false
NaN false false
5.0+0.0i true true
5-5i false false
</pre>
 
Line 2,235 ⟶ 2,804:
The simplest way is to test whether the value is (numerically) equal to itself cast as an integer. entier() performs this cast without imposing any word-size limits (as int() or wide() would).
 
<langsyntaxhighlight lang="tcl">proc isNumberIntegral {x} {
expr {$x == entier($x)}
}
Line 2,241 ⟶ 2,810:
foreach x {1e100 3.14 7 1.000000000000001 1000000000000000000000 -22.7 -123.000} {
puts [format "%s: %s" $x [expr {[isNumberIntegral $x] ? "yes" : "no"}]]
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,255 ⟶ 2,824:
Note that 1.0000000000000001 will pass this integer test, because its difference from 1.0 is beyond the precision of an IEEE binary64 float. This discrepancy will be visible in other languages, but perhaps more obvious in Tcl as such a value's string representation will persist:
 
<langsyntaxhighlight Tcllang="tcl">% set a 1.0000000000000001
1.0000000000000001
% expr $a
Line 2,262 ⟶ 2,831:
1
% puts $a
1.0000000000000001</langsyntaxhighlight>
 
compare Python:
 
<langsyntaxhighlight Pythonlang="python">>>> a = 1.0000000000000001
>>> a
1.0
>>> 1.0 == 1.0000000000000001
True</langsyntaxhighlight>
 
.. this is a fairly benign illustration of why comparing floating point values with == is usually a bad idea.
 
=={{header|Wren}}==
{{libheader|Wren-big}}
{{libheader|Wren-complex}}
{{libheader|Wren-rat}}
{{libheader|Wren-fmt}}
The -2e120 example requires the use of BigRat to reliably determine whether it's an integer or not. Although the Num class can deal with numbers of this size and correctly identifies it as an integer, it would do the same if (say) 0.5 were added to it because integer determination is only reliable up to around 15 digits.
<syntaxhighlight lang="wren">import "./big" for BigRat
import "./complex" for Complex
import "./rat" for Rat
import "./fmt" for Fmt
 
var tests1 = [25.000000, 24.999999, 25.000100]
var tests2 = ["-2.1e120"]
var tests3 = [-5e-2, 0/0, 1/0]
var tests4 = [Complex.fromString("5.0+0.0i"), Complex.fromString("5-5i")]
var tests5 = [Rat.new(24, 8), Rat.new(-5, 1), Rat.new(17, 2)]
var tests6 = tests1 + [-5e-2]
 
System.print("Using exact arithmetic:\n")
for (t in tests1) {
Fmt.print(" $-9.6f is integer? $s", t, t.isInteger)
}
System.print()
for (t in tests2) {
Fmt.print(" $-9s is integer? $s", t, BigRat.new(t, 1).isInteger)
}
for (t in tests3) {
Fmt.print(" $-9.6f is integer? $s", t, t.isInteger)
}
System.print()
for (t in tests4) {
Fmt.print(" $-9s is integer? $s", t, t.isRealInteger)
}
System.print()
for (t in tests5) {
Fmt.print(" $-9s is integer? $s", t, t.isInteger)
}
System.print("\nWithin a tolerance of 0.00001:\n")
var tol = 0.00001
for (t in tests6) {
var d = (t - t.round).abs
Fmt.print(" $9.6f is integer? $s", t, d <= tol)
}</syntaxhighlight>
 
{{out}}
<pre>
Using exact arithmetic:
 
25.000000 is integer? true
24.999999 is integer? false
25.000100 is integer? false
 
-2.1e120 is integer? true
-0.050000 is integer? false
nan is integer? false
infinity is integer? false
 
5 + 0i is integer? true
5 - 5i is integer? false
 
3/1 is integer? true
-5/1 is integer? true
17/2 is integer? false
 
Within a tolerance of 0.00001:
 
25.000000 is integer? true
24.999999 is integer? true
25.000100 is integer? false
-0.050000 is integer? false
</pre>
 
=={{header|XPL0}}==
XPL0 has two data types: signed 32-bit integer and 8-byte real
represented by the processor's FPU (normally IEEE 754 double format). This
test program fails by stating that -2e10 is not an integer. However, it
is not an XPL0 integer that can be represented by a 32-bit signed value.
 
<syntaxhighlight lang="xpl0">real R;
[Format(20, 20);
repeat R:= RlIn(0);
RlOut(0, R);
Text(0, if R = float(fix(R)) then " is integer"
else " is not integer");
CrLf(0);
until R = 0.;
]</syntaxhighlight>
 
{{out}}
<pre>
25.000000 25.00000000000000000000 is integer
24.999999 24.99999900000000000000 is not integer
24.9999999999999999 25.00000000000000000000 is integer
25.00001 25.00001000000000000000 is not integer
-2e9 -2000000000.00000000000000000000 is integer
-2e10 -20000000000.00000000000000000000 is not integer
-5e-1 -0.50000000000000000000 is not integer
0 0.00000000000000000000 is integer
</pre>
 
=={{header|zkl}}==
No complex type.
<langsyntaxhighlight lang="zkl">T(1, 2.0,4.1,"nope",self).apply((1).isType)</langsyntaxhighlight>
{{out}}<pre>L(True,False,False,False,False)</pre>
All is not golden as BigInts (lib GMP) don't consider themselves to be integers so the above test would fail. For that case:
<langsyntaxhighlight lang="zkl">fcn isInt(x){ try{x==x.toInt()}catch{False}}
var BN=Import("zklBigNum");
T(1, 2.0,4.1,"nope",self,BN(5)).apply(isInt);</langsyntaxhighlight>
{{out}}<pre>L(True,True,False,False,False,True)</pre>
Note that the first float is now considered to have an integer equivalent.
1,982

edits