Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,2 @@
---
from: http://rosettacode.org/wiki/Test_integerness

View file

@ -0,0 +1,112 @@
Mathematically,
* the [[wp:Integer|integers]] '''Z''' are included in the [[wp:Rational number|rational numbers]] '''Q''',
* which are included in the [[wp:Real number|real numbers]] '''R''',
* which can be generalized to the [[wp:Complex number|complex numbers]] '''C'''.
This means that each of those larger sets, and the data types used to represent them, include some integers.
{{task heading}}
Given a rational, real, or complex number of any type, test whether it is mathematically an integer.
Your code should handle all numeric data types commonly used in your programming language.
Discuss any limitations of your code.
{{task heading|Definition}}
For the purposes of this task, integerness means that a number could theoretically be represented as an integer at no loss of precision ''<small>(given an infinitely wide integer type)</small>''.<br>
In other words:
{| class="wikitable"
|-
! Set
! Common representation
! C++ type
! Considered an integer...
|-
| rational numbers '''Q'''
| [[wp:Rational data type|fraction]]
| <code>std::ratio</code>
| ...if its denominator is 1 (in reduced form)
|-
| rowspan=2 | real numbers '''Z'''<br><small>''(approximated)''</small>
| [[wp:Fixed-point arithmetic|fixed-point]]
|
| ...if it has no non-zero digits after the decimal point
|-
| [[wp:Floating point|floating-point]]
| <code>float</code>, <code>double</code>
| ...if the number of significant decimal places of its mantissa isn't greater than its exponent
|-
| complex numbers '''C'''
| [[wp:Complex data type|pair of real numbers]]
| <code>std::complex</code>
| ...if its real part is considered an integer and its imaginary part is zero
|}
{{task heading|Extra credit}}
Optionally, make your code accept a <code>tolerance</code> parameter for fuzzy testing. The tolerance is the maximum amount by which the number may differ from the nearest integer, to still be considered an integer.
This is useful in practice, because when dealing with approximate numeric types (such as floating point), there may already be [[wp:Round-off error|round-off errors]] from previous calculations. For example, a float value of <code>0.9999999998</code> might actually be intended to represent the integer <code>1</code>.
{{task heading|Test cases}}
{| class="wikitable"
|-
! colspan=2 | Input
! colspan=2 | Output
! rowspan=2 | Comment
|-
! <small>Type</small>
! <small>Value</small>
! <small><tt>exact</tt></small>
! <small><tt>tolerance = 0.00001</tt></small>
|-
| rowspan=3 | decimal
| <code>25.000000</code>
| colspan=2 | true
|
|-
| <code>24.999999</code>
| false
| true
|
|-
| <code>25.000100</code>
| colspan=2 | false
|
|-
| rowspan=4 | floating-point
| <code>-2.1e120</code>
| colspan=2 | true
| This one is tricky, because in most languages it is too large to fit into a native integer type.<br>It is, nonetheless, mathematically an integer, and your code should identify it as such.
|-
| <code>-5e-2</code>
| colspan=2 | false
|
|-
| <code>NaN</code>
| colspan=2 | false
|
|-
| <code>Inf</code>
| colspan=2 | false
| This one is debatable. If your code considers it an integer, that's okay too.
|-
| rowspan=2 | complex
| <code>5.0+0.0i</code>
| colspan=2 | true
|
|-
| <code>5-5i</code>
| colspan=2 | false
|
|}
(The types and notations shown in these tables are merely examples &ndash; you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)
<hr>

View file

@ -0,0 +1,11 @@
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))

View file

@ -0,0 +1,25 @@
# set the required precision of LONG LONG values using #
# "PR precision n PR" if required #
PR precision 24 PR
# returns TRUE if v has an integer value, FALSE otherwise #
OP ISINT = ( LONG LONG COMPL v )BOOL:
IF im OF v /= 0 THEN
# v has an imaginary part #
FALSE
ELSE
# v has a real part only #
ENTIER re OF v = v
FI; # ISINT #
# test ISINT #
PROC test is int = ( LONG LONG COMPLEX v )VOID:
print( ( re OF v, "_", im OF v, IF ISINT v THEN " is " ELSE " is not " FI, "integral", newline ) );
test is int( 1 );
test is int( 1.00000001 );
test is int( 4 I 3 );
test is int( 4.0 I 0 );
test is int( 123456789012345678901234 )

View file

@ -0,0 +1,10 @@
# 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)
}

View file

@ -0,0 +1,169 @@
#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;
}

View file

@ -0,0 +1,128 @@
namespace Test_integerness
{
class Program
{
public static void Main(string[] args)
{
Console.Clear();
Console.WriteLine();
Console.WriteLine(" ***************************************************");
Console.WriteLine(" * *");
Console.WriteLine(" * Integerness test *");
Console.WriteLine(" * *");
Console.WriteLine(" ***************************************************");
Console.WriteLine();
ConsoleKeyInfo key = new ConsoleKeyInfo('Y',ConsoleKey.Y,true,true,true);
while(key.Key == ConsoleKey.Y)
{
// Get number value from keyboard
Console.Write(" Enter number value : ");
string LINE = Console.ReadLine();
// Get tolerance value from keyboard
Console.Write(" Enter tolerance value : ");
double TOLERANCE = double.Parse(Console.ReadLine());
// Resolve entered number format and set NUMBER value
double NUMBER = 0;
string [] N;
// Real number value
if(!double.TryParse(LINE, out NUMBER))
{
// Rational number value
if(LINE.Contains("/"))
{
N = LINE.Split('/');
NUMBER = double.Parse(N[0]) / double.Parse(N[1]);
}
// Inf value
else if(LINE.ToUpper().Contains("INF"))
{
NUMBER = double.PositiveInfinity;
}
// Complex value
else if(LINE.ToUpper().Contains("I"))
{
// Delete letter i
LINE = LINE.ToUpper().Replace("I","");
string r = string.Empty; // real part
string i = string.Empty; // imaginary part
int s = 1; // sign offset
// Get sign
if(LINE[0]=='+' || LINE[0]=='-')
{
r+=LINE[0].ToString();
LINE = LINE.Remove(0,1);
s--;
}
// Get real part
foreach (char element in LINE)
{
if(element!='+' && element!='-')
r+=element.ToString();
else
break;
}
// get imaginary part
i = LINE.Substring(LINE.Length-(r.Length+s));
NUMBER = double.Parse(i);
if(NUMBER==0)
NUMBER = double.Parse(r);
else
NUMBER = double.NaN;
}
// NaN value
else
NUMBER = double.NaN;
}
// Test
bool IS_INTEGER = false;
bool IS_INTEGER_T = false;
if(double.IsNaN(NUMBER))
IS_INTEGER=false;
else if(Math.Round(NUMBER,0).ToString() == NUMBER.ToString())
IS_INTEGER = true;
else if((decimal)TOLERANCE >= (decimal)Math.Abs( (decimal)Math.Round(NUMBER,0) - (decimal)NUMBER ))
IS_INTEGER_T = true;
if(IS_INTEGER)
Console.WriteLine(" Is exact integer " + IS_INTEGER);
else
{
Console.WriteLine( " Is exact integer " + IS_INTEGER );
Console.WriteLine( " Is integer with tolerance " + IS_INTEGER_T );
}
Console.WriteLine();
Console.Write(" Another test < Y /N > . . . ");
key = Console.ReadKey(true);
Console.WriteLine();
Console.WriteLine();
}
}
}
}

View file

@ -0,0 +1,57 @@
#include <stdio.h>
#include <complex.h>
#include <math.h>
/* Testing macros */
#define FMTSPEC(arg) _Generic((arg), \
float: "%f", double: "%f", \
long double: "%Lf", unsigned int: "%u", \
unsigned long: "%lu", unsigned long long: "%llu", \
int: "%d", long: "%ld", long long: "%lld", \
default: "(invalid type (%p)")
#define CMPPARTS(x, y) ((long double complex)((long double)(x) + \
I * (long double)(y)))
#define TEST_CMPL(i, j)\
printf(FMTSPEC(i), i), printf(" + "), printf(FMTSPEC(j), j), \
printf("i = %s\n", (isint(CMPPARTS(i, j)) ? "true" : "false"))
#define TEST_REAL(i)\
printf(FMTSPEC(i), i), printf(" = %s\n", (isint(i) ? "true" : "false"))
/* Main code */
static inline int isint(long double complex n)
{
return cimagl(n) == 0 && nearbyintl(creall(n)) == creall(n);
}
int main(void)
{
TEST_REAL(0);
TEST_REAL(-0);
TEST_REAL(-2);
TEST_REAL(-2.00000000000001);
TEST_REAL(5);
TEST_REAL(7.3333333333333);
TEST_REAL(3.141592653589);
TEST_REAL(-9.223372036854776e18);
TEST_REAL(5e-324);
TEST_REAL(NAN);
TEST_CMPL(6, 0);
TEST_CMPL(0, 1);
TEST_CMPL(0, 0);
TEST_CMPL(3.4, 0);
/* Demonstrating that we can use the same function for complex values
* constructed in the standard way */
double complex test1 = 5 + 0*I,
test2 = 3.4f,
test3 = 3,
test4 = 0 + 1.2*I;
printf("Test 1 (5+i) = %s\n", isint(test1) ? "true" : "false");
printf("Test 2 (3.4+0i) = %s\n", isint(test2) ? "true" : "false");
printf("Test 3 (3+0i) = %s\n", isint(test3) ? "true" : "false");
printf("Test 4 (0+1.2i) = %s\n", isint(test4) ? "true" : "false");
}

View file

@ -0,0 +1,35 @@
IDENTIFICATION DIVISION.
PROGRAM-ID. INTEGERNESS-PROGRAM.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 INTEGERS-OR-ARE-THEY.
05 POSSIBLE-INTEGER PIC S9(9)V9(9).
05 DEFINITE-INTEGER PIC S9(9).
01 COMPLEX-NUMBER.
05 REAL-PART PIC S9(9)V9(9).
05 IMAGINARY-PART PIC S9(9)V9(9).
PROCEDURE DIVISION.
TEST-PARAGRAPH.
MOVE ZERO TO IMAGINARY-PART.
DIVIDE -28 BY 7 GIVING POSSIBLE-INTEGER.
PERFORM INTEGER-PARAGRAPH.
DIVIDE 28 BY 18 GIVING POSSIBLE-INTEGER.
PERFORM INTEGER-PARAGRAPH.
DIVIDE 3 BY 10000000000 GIVING POSSIBLE-INTEGER.
PERFORM INTEGER-PARAGRAPH.
TEST-COMPLEX-PARAGRAPH.
MOVE ZERO TO REAL-PART.
MOVE 1 TO IMAGINARY-PART.
MOVE REAL-PART TO POSSIBLE-INTEGER.
PERFORM INTEGER-PARAGRAPH.
STOP RUN.
INTEGER-PARAGRAPH.
IF IMAGINARY-PART IS EQUAL TO ZERO THEN PERFORM REAL-PARAGRAPH,
ELSE PERFORM COMPLEX-PARAGRAPH.
REAL-PARAGRAPH.
MOVE POSSIBLE-INTEGER TO DEFINITE-INTEGER.
IF DEFINITE-INTEGER IS EQUAL TO POSSIBLE-INTEGER
THEN DISPLAY POSSIBLE-INTEGER ' IS AN INTEGER.',
ELSE DISPLAY POSSIBLE-INTEGER ' IS NOT AN INTEGER.'.
COMPLEX-PARAGRAPH.
DISPLAY REAL-PART '+' IMAGINARY-PART 'i IS NOT AN INTEGER.'.

View file

@ -0,0 +1,87 @@
import std.complex;
import std.math;
import std.meta;
import std.stdio;
import std.traits;
void main() {
print(25.000000);
print(24.999999);
print(24.999999, 0.00001);
print(25.000100);
print(-2.1e120);
print(-5e-2);
print(real.nan);
print(real.infinity);
print(5.0+0.0i);
print(5-5i);
}
void print(T)(T v, real tol = 0.0) {
writefln("Is %0.10s an integer? %s", v, isInteger(v, tol));
}
/// Test for plain integers
bool isInteger(T)(T v)
if (isIntegral!T) {
return true;
}
unittest {
assert(isInteger(5));
assert(isInteger(-5));
assert(isInteger(2L));
assert(isInteger(-2L));
}
/// Test for floating point
bool isInteger(T)(T v, real tol = 0.0)
if (isFloatingPoint!T) {
return (v - floor(v)) <= tol || (ceil(v) - v) <= tol;
}
unittest {
assert(isInteger(25.000000));
assert(!isInteger(24.999999));
assert(isInteger(24.999999, 0.00001));
}
/// Test for complex numbers
bool isInteger(T)(Complex!T v, real tol = 0.0) {
return isInteger(v.re, tol) && abs(v.im) <= tol;
}
unittest {
assert(isInteger(complex(1.0)));
assert(!isInteger(complex(1.0, 0.0001)));
assert(isInteger(complex(1.0, 0.00009), 0.0001));
}
/// Test for built-in complex types
bool isInteger(T)(T v, real tol = 0.0)
if (staticIndexOf!(Unqual!T, AliasSeq!(cfloat, cdouble, creal)) >= 0) {
return isInteger(v.re, tol) && abs(v.im) <= tol;
}
unittest {
assert(isInteger(1.0 + 0.0i));
assert(!isInteger(1.0 + 0.0001i));
assert(isInteger(1.0 + 0.00009i, 0.0001));
}
/// Test for built-in imaginary types
bool isInteger(T)(T v, real tol = 0.0)
if (staticIndexOf!(Unqual!T, AliasSeq!(ifloat, idouble, ireal)) >= 0) {
return abs(v) <= tol;
}
unittest {
assert(isInteger(0.0i));
assert(!isInteger(0.0001i));
assert(isInteger(0.00009i, 0.0001));
}

View file

@ -0,0 +1,72 @@
{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;

View file

@ -0,0 +1,8 @@
defmodule Test do
def integer?(n) when n == trunc(n), do: true
def integer?(_), do: false
end
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)

View file

@ -0,0 +1,36 @@
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

View file

@ -0,0 +1,28 @@
MODULE ZERMELO !Approach the foundations of mathematics.
CONTAINS
LOGICAL FUNCTION ISINTEGRAL(X) !A whole number?
REAL*8 X !Alas, this is not really a REAL number.
INTEGER*8 N !Largest available.
IF (ISNAN(X)) THEN !Avoid some sillyness.
ISINTEGRAL = .FALSE. !And possible error messages.
ELSE !But now it is safe to try.
N = KIDINT(X) !This one truncates.
ISINTEGRAL = N .EQ. X !Any difference?
END IF !A floating-point number may overflow an integer.
END FUNCTION ISINTEGRAL !And even if integral, it will not seem so.
LOGICAL FUNCTION ISINTEGRALZ(Z) !For complex numbers, two tests.
DOUBLE COMPLEX Z !Still not really REAL, though.
ISINTEGRALZ = ISINTEGRAL(DBLE(Z)) .AND. ISINTEGRAL(DIMAG(Z)) !Separate the parts.
END FUNCTION ISINTEGRALZ!No INTEGER COMPLEX type is offered.
END MODULE ZERMELO !Much more mathematics lie elsewhere.
PROGRAM TEST
USE ZERMELO
DOUBLE COMPLEX Z
WRITE (6,*) "See if some numbers are integral..."
WRITE (6,*) ISINTEGRAL(666D0),666D0
Z = DCMPLX(-3D0,4*ATAN(1D0))
WRITE (6,*) ISINTEGRALZ(Z),Z
END

View file

@ -0,0 +1,5 @@
X = 1
10 X = X*BASE
Y = X + 1
D = Y - X
IF (D .EQ. 1) GO TO 10

View file

@ -0,0 +1,61 @@
MODULE ZERMELO !Approach the foundations of mathematics.
INTERFACE ISINTEGRAL !And obscure them with computerese.
MODULE PROCEDURE ISINTEGRALF4, ISINTEGRALF8,
1 ISINTEGRALZ8, ISINTEGRALZ16
END INTERFACE !Selection is by parameter type and number.
CONTAINS !Sop, now for a grabbag of routines.
LOGICAL FUNCTION ISINTEGRALF8(X) !A whole number?
REAL*8 X !Alas, this is not really a REAL number.
INTEGER*8 N !Largest available.
INTEGER*8 BIG !The first number too big to have any fractional digits in floating-point.
PARAMETER (BIG = RADIX(X)**(DIGITS(X) - 1)) !These "functions" are in fact constants.
IF (ISNAN(X)) THEN !Avoid some sillyness.
ISINTEGRALF8 = .FALSE. !And possible error messages.
ELSE IF (ABS(X).GE.BIG) THEN !But now it is safe to try.
ISINTEGRALF8 = .TRUE. !Can't have fractional digits => integral.
ELSE !But smaller numbers can have fractional digits.
N = KIDINT(X) !So, truncate to an integral value.
ISINTEGRALF8 = N .EQ. X !Any difference?
END IF !So much for inspection.
END FUNCTION ISINTEGRALF8 !No need to look at digit sequences.
LOGICAL FUNCTION ISINTEGRALF4(X) !A whole number?
REAL*4 X !Alas, this is not really a REAL number.
INTEGER*4 N !Largest available.
IF (ISNAN(X)) THEN !Avoid some sillyness.
ISINTEGRALF4 = .FALSE. !And possible error messages.
ELSE IF (ABS(X) .GE. RADIX(X)**(DIGITS(X) - 1)) THEN !Constant results as appropriate for X.
ISINTEGRALF4 = .TRUE. !Can't have fractional digits => integral.
ELSE !But smaller numbers can have fractional digits.
N = INT(X) !So, truncate to an integral value.
ISINTEGRALF4 = N .EQ. X !Any difference?
END IF !A real*4 should not overflow INTEGER*4.
END FUNCTION ISINTEGRALF4 !Thanks to the size check.
LOGICAL FUNCTION ISINTEGRALZ8(Z) !For complex numbers, two tests.
COMPLEX Z !Still not really REAL, though.
ISINTEGRALZ8 = ISINTEGRAL(REAL(Z)) .AND. ISINTEGRAL(AIMAG(Z)) !Separate the parts.
END FUNCTION ISINTEGRALZ8 !No INTEGER COMPLEX type is offered.
LOGICAL FUNCTION ISINTEGRALZ16(Z) !And there are two sorts of complex numbers.
DOUBLE COMPLEX Z !Still not really REAL.
ISINTEGRALZ16 = ISINTEGRAL(DBLE(Z)) .AND. ISINTEGRAL(DIMAG(Z)) !Separate the parts.
END FUNCTION ISINTEGRALZ16 !No INTEGER COMPLEX type is offered.
END MODULE ZERMELO !Much more mathematics lie elsewhere.
PROGRAM TEST
USE ZERMELO
DOUBLE COMPLEX Z
DOUBLE PRECISION X
REAL U
Cast forth some pearls.
WRITE (6,1) 4,DIGITS(U),RADIX(U)
WRITE (6,1) 8,DIGITS(X),RADIX(X)
1 FORMAT ("REAL*",I1,":",I3," digits, in base",I2)
WRITE (6,*) "See if some numbers are integral..."
WRITE (6,*) ISINTEGRAL(666D0),666D0
WRITE (6,*) ISINTEGRAL(665.9),665.9
Z = DCMPLX(-3D0,4*ATAN(1D0))
WRITE (6,*) ISINTEGRAL(Z),Z
END

View file

@ -0,0 +1,58 @@
// 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` isnt 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.

View file

@ -0,0 +1,12 @@
#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

View file

@ -0,0 +1,157 @@
package main
import (
"fmt"
"math"
"math/big"
"reflect"
"strings"
"unsafe"
)
// Go provides an integerness test only for the big.Rat and big.Float types
// in the standard library.
// The fundamental piece of code needed for built-in floating point types
// is a test on the float64 type:
func Float64IsInt(f float64) bool {
_, frac := math.Modf(f)
return frac == 0
}
// Other built-in or stanadard library numeric types are either always
// integer or can be easily tested using Float64IsInt.
func Float32IsInt(f float32) bool {
return Float64IsInt(float64(f))
}
func Complex128IsInt(c complex128) bool {
return imag(c) == 0 && Float64IsInt(real(c))
}
func Complex64IsInt(c complex64) bool {
return imag(c) == 0 && Float64IsInt(float64(real(c)))
}
// Usually just the above statically typed functions would be all that is used,
// but if it is desired to have a single function that can test any arbitrary
// type, including the standard math/big types, user defined types based on
// an integer, float, or complex builtin types, or user defined types that
// have an IsInt() method, then reflection can be used.
type hasIsInt interface {
IsInt() bool
}
var bigIntT = reflect.TypeOf((*big.Int)(nil))
func IsInt(i interface{}) bool {
if ci, ok := i.(hasIsInt); ok {
// Handles things like *big.Rat
return ci.IsInt()
}
switch v := reflect.ValueOf(i); v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16,
reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16,
reflect.Uint32, reflect.Uint64, reflect.Uintptr:
// Built-in types and any custom type based on them
return true
case reflect.Float32, reflect.Float64:
// Built-in floats and anything based on them
return Float64IsInt(v.Float())
case reflect.Complex64, reflect.Complex128:
// Built-in complexes and anything based on them
return Complex128IsInt(v.Complex())
case reflect.String:
// Could also do strconv.ParseFloat then FloatIsInt but
// big.Rat handles everything ParseFloat can plus more.
// Note, there is no strconv.ParseComplex.
if r, ok := new(big.Rat).SetString(v.String()); ok {
return r.IsInt()
}
case reflect.Ptr:
// Special case for math/big.Int
if v.Type() == bigIntT {
return true
}
}
return false
}
// The rest is just demonstration and display
type intbased int16
type complexbased complex64
type customIntegerType struct {
// Anything that stores or represents a sub-set
// of integer values in any way desired.
}
func (customIntegerType) IsInt() bool { return true }
func (customIntegerType) String() string { return "<…>" }
func main() {
hdr := fmt.Sprintf("%27s %-6s %s\n", "Input", "IsInt", "Type")
show2 := func(t bool, i interface{}, args ...interface{}) {
istr := fmt.Sprint(i)
fmt.Printf("%27s %-6t %T ", istr, t, i)
fmt.Println(args...)
}
show := func(i interface{}, args ...interface{}) {
show2(IsInt(i), i, args...)
}
fmt.Print("Using Float64IsInt with float64:\n", hdr)
neg1 := -1.
for _, f := range []float64{
0, neg1 * 0, -2, -2.000000000000001, 10. / 2, 22. / 3,
math.Pi,
math.MinInt64, math.MaxUint64,
math.SmallestNonzeroFloat64, math.MaxFloat64,
math.NaN(), math.Inf(1), math.Inf(-1),
} {
show2(Float64IsInt(f), f)
}
fmt.Print("\nUsing Complex128IsInt with complex128:\n", hdr)
for _, c := range []complex128{
3, 1i, 0i, 3.4,
} {
show2(Complex128IsInt(c), c)
}
fmt.Println("\nUsing reflection:")
fmt.Print(hdr)
show("hello")
show(math.MaxFloat64)
show("9e100")
f := new(big.Float)
show(f)
f.SetString("1e-3000")
show(f)
show("(4+0i)", "(complex strings not parsed)")
show(4 + 0i)
show(rune('§'), "or rune")
show(byte('A'), "or byte")
var t1 intbased = 5200
var t2a, t2b complexbased = 5 + 0i, 5 + 1i
show(t1)
show(t2a)
show(t2b)
x := uintptr(unsafe.Pointer(&t2b))
show(x)
show(math.MinInt32)
show(uint64(math.MaxUint64))
b, _ := new(big.Int).SetString(strings.Repeat("9", 25), 0)
show(b)
r := new(big.Rat)
show(r)
r.SetString("2/3")
show(r)
show(r.SetFrac(b, new(big.Int).SetInt64(9)))
show("12345/5")
show(new(customIntegerType))
}

View file

@ -0,0 +1,3 @@
import Data.Decimal
import Data.Ratio
import Data.Complex

View file

@ -0,0 +1,2 @@
class ContainsInteger a where
isInteger :: a -> Bool

View file

@ -0,0 +1,2 @@
instance ContainsInteger Int where isInteger _ = True
instance ContainsInteger Integer where isInteger _ = True

View file

@ -0,0 +1,6 @@
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

View file

@ -0,0 +1,2 @@
instance (Eq a, Num a, ContainsInteger a) => ContainsInteger (Complex a) where
isInteger z = isInteger (realPart z) && (imagPart z == 0)

View file

@ -0,0 +1,7 @@
x ~~ eps = abs x <= eps
almostInteger :: RealFrac a => a -> a -> Bool
almostInteger eps x = (x - fromInteger (round x)) ~~ eps
almostIntegerC :: RealFrac a => a -> Complex a -> Bool
almostIntegerC eps z = almostInteger eps (realPart z) && (imagPart z) ~~ eps

View file

@ -0,0 +1,25 @@
tests = all (== True)
[ isInteger (5 :: Integer)
, isInteger (5.0 :: Decimal)
, isInteger (-5 :: Integer)
, isInteger (0 :: Decimal)
, isInteger (-2.1e120 :: Double)
, isInteger (5 % 1 :: Rational)
, isInteger (4 % 2 :: Rational)
, isInteger (5 :+ 0 :: Complex Integer)
, isInteger (5.0 :+ 0.0 :: Complex Decimal)
, isInteger (6 % 3 :+ 0 :: Complex Rational)
, isInteger (1/0 :: Double) -- Infinity is integer
, isInteger (1.1/0 :: Double) -- Infinity is integer
, not $ isInteger (5.01 :: Decimal)
, not $ isInteger (-5e-2 :: Double)
, not $ isInteger (5 % 3 :: Rational)
, not $ isInteger (5 :+ 1 :: Complex Integer)
, not $ isInteger (6 % 4 :+ 0 :: Complex Rational)
, not $ isInteger (5.0 :+ 1.0 :: Complex Decimal)
, almostInteger 0.01 2.001
, almostInteger 0.01 (-1.999999)
, almostInteger (1 % 10) (24 % 23)
, not $ almostInteger 0.01 2.02
, almostIntegerC 0.001 (5.999999 :+ 0.000001)
]

View file

@ -0,0 +1,6 @@
pithagoreanTriangles :: [[Integer]]
pithagoreanTriangles =
[ [a, b, round c] | b <- [1..]
, a <- [1..b]
, let c = sqrt (fromInteger (a^2 + b^2))
, isInteger (c :: Double) ]

View file

@ -0,0 +1 @@
isInt =: (= <.) *. (= {.@+.)

View file

@ -0,0 +1 @@
isInt=: (0 = 1&|) *. (0 = {:@+.)

View file

@ -0,0 +1,2 @@
isInt 3.14 7 1.4j0 4j0 5j3 5r3 6r3
0 1 0 1 0 0 1

View file

@ -0,0 +1,100 @@
import java.math.BigDecimal;
import java.util.List;
public class TestIntegerness {
private static boolean isLong(double d) {
return isLong(d, 0.0);
}
private static boolean isLong(double d, double tolerance) {
return (d - Math.floor(d)) <= tolerance || (Math.ceil(d) - d) <= tolerance;
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private static boolean isBigInteger(BigDecimal bd) {
try {
bd.toBigIntegerExact();
return true;
} catch (ArithmeticException ex) {
return false;
}
}
private static class Rational {
long num;
long denom;
Rational(int num, int denom) {
this.num = num;
this.denom = denom;
}
boolean isLong() {
return num % denom == 0;
}
@Override
public String toString() {
return String.format("%s/%s", num, denom);
}
}
private static class Complex {
double real;
double imag;
Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
boolean isLong() {
return TestIntegerness.isLong(real) && imag == 0.0;
}
@Override
public String toString() {
if (imag >= 0.0) {
return String.format("%s + %si", real, imag);
}
return String.format("%s - %si", real, imag);
}
}
public static void main(String[] args) {
List<Double> da = List.of(25.000000, 24.999999, 25.000100);
for (Double d : da) {
boolean exact = isLong(d);
System.out.printf("%.6f is %s integer%n", d, exact ? "an" : "not an");
}
System.out.println();
double tolerance = 0.00001;
System.out.printf("With a tolerance of %.5f:%n", tolerance);
for (Double d : da) {
boolean fuzzy = isLong(d, tolerance);
System.out.printf("%.6f is %s integer%n", d, fuzzy ? "an" : "not an");
}
System.out.println();
List<Double> fa = List.of(-2.1e120, -5e-2, Double.NaN, Double.POSITIVE_INFINITY);
for (Double f : fa) {
boolean exact = !f.isNaN() && !f.isInfinite() && isBigInteger(new BigDecimal(f.toString()));
System.out.printf("%s is %s integer%n", f, exact ? "an" : "not an");
}
System.out.println();
List<Complex> ca = List.of(new Complex(5.0, 0.0), new Complex(5.0, -5.0));
for (Complex c : ca) {
boolean exact = c.isLong();
System.out.printf("%s is %s integer%n", c, exact ? "an" : "not an");
}
System.out.println();
List<Rational> ra = List.of(new Rational(24, 8), new Rational(-5, 1), new Rational(17, 2));
for (Rational r : ra) {
boolean exact = r.isLong();
System.out.printf("%s is %s integer%n", r, exact ? "an" : "not an");
}
}
}

View file

@ -0,0 +1,10 @@
def is_integral:
if type == "number" then . == floor
elif type == "array" then
length == 2 and .[1] == 0 and (.[0] | is_integral)
else type == "object"
and .type == "rational"
and .q != 0
and (.q | is_integral)
and ((.p / .q) | is_integral)
end ;

View file

@ -0,0 +1,4 @@
(
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)"

View file

@ -0,0 +1,9 @@
$ jq -r -n -f is_integral.jq
0 => integral
-1 => integral
[3,0] => integral
{"p":4,"q":2,"type":"rational"} => integral
1.1 =>
-1.1 =>
[3,1] =>
{"p":5,"q":2,"type":"rational"} =>

View file

@ -0,0 +1,11 @@
# v0.6.0
@show isinteger(25.000000)
@show isinteger(24.999999)
@show isinteger(25.000100)
@show isinteger(-2.1e120)
@show isinteger(-5e-2)
@show isinteger(NaN)
@show isinteger(Inf)
@show isinteger(complex(5.0, 0.0))
@show isinteger(complex(5, 5))

View file

@ -0,0 +1,68 @@
// version 1.1.2
import java.math.BigInteger
import java.math.BigDecimal
fun Double.isLong(tolerance: Double = 0.0) =
(this - Math.floor(this)) <= tolerance || (Math.ceil(this) - this) <= tolerance
fun BigDecimal.isBigInteger() =
try {
this.toBigIntegerExact()
true
}
catch (ex: ArithmeticException) {
false
}
class Rational(val num: Long, val denom: Long) {
fun isLong() = num % denom == 0L
override fun toString() = "$num/$denom"
}
class Complex(val real: Double, val imag: Double) {
fun isLong() = real.isLong() && imag == 0.0
override fun toString() =
if (imag >= 0.0)
"$real + ${imag}i"
else
"$real - ${-imag}i"
}
fun main(args: Array<String>) {
val da = doubleArrayOf(25.000000, 24.999999, 25.000100)
for (d in da) {
val exact = d.isLong()
println("${"%.6f".format(d)} is ${if (exact) "an" else "not an"} integer")
}
val tolerance = 0.00001
println("\nWith a tolerance of ${"%.5f".format(tolerance)}:")
for (d in da) {
val fuzzy = d.isLong(tolerance)
println("${"%.6f".format(d)} is ${if (fuzzy) "an" else "not an"} integer")
}
println()
val fa = doubleArrayOf(-2.1e120, -5e-2, Double.NaN, Double.POSITIVE_INFINITY)
for (f in fa) {
val exact = if (f.isNaN() || f.isInfinite()) false
else BigDecimal(f.toString()).isBigInteger()
println("$f is ${if (exact) "an" else "not an"} integer")
}
println()
val ca = arrayOf(Complex(5.0, 0.0), Complex(5.0, -5.0))
for (c in ca) {
val exact = c.isLong()
println("$c is ${if (exact) "an" else "not an"} integer")
}
println()
val ra = arrayOf(Rational(24, 8), Rational(-5, 1), Rational(17, 2))
for (r in ra) {
val exact = r.isLong()
println("$r is ${if (exact) "an" else "not an"} integer")
}
}

View file

@ -0,0 +1,6 @@
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

View file

@ -0,0 +1 @@
IntegerQ /@ {E, 2.4, 7, 9/2}

View file

@ -0,0 +1,31 @@
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

View file

@ -0,0 +1,60 @@
/* 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
Call test_integer .complex~new(1e+12,0e-3)
Call test_integer .complex~new(3.14)
Call test_integer .complex~new(1.00000)
Call test_integer .complex~new(33)
Call test_integer .complex~new(999999999)
Call test_integer .complex~new(99999999999)
Call test_integer .complex~new(1e272)
Call test_integer .complex~new(0)
Call test_integer .complex~new(1.000,-3)
Call test_integer .complex~new(1.000,-3.3)
Call test_integer .complex~new(,4)
Call test_integer .complex~new(2.00000000,+0)
Call test_integer .complex~new(,0)
Call test_integer .complex~new(333)
Call test_integer .complex~new(-1,-1)
Call test_integer .complex~new(1,1)
Call test_integer .complex~new(,.00)
Call test_integer .complex~new(,1)
Call test_integer .complex~new(0003,00.0)
Exit
test_integer:
Use Arg cpx
cpxa=left(changestr('+-',cpx,'-'),13) -- beautify representation
Select
When cpx~imaginary<>0 Then
Say cpxa 'is not an integer'
When datatype(cpx~real,'W') Then
Say cpxa 'is an integer'
Otherwise
Say cpxa 'is not an integer'
End
Return
::class complex
::method init /* initialize a complex number */
expose real imaginary /* expose the state data */
use Strict arg first=0, second=0 /* access the two numbers */
real = first + 0 /* force rounding */
imaginary = second + 0 /* force rounding on the second */
::method real /* return real part of a complex */
expose real /* access the state information */
return real /* return that value */
::method imaginary /* return imaginary part */
expose imaginary /* access the state information */
return imaginary /* return the value */
::method string /* format as a string value */
expose real imaginary /* get the state info */
return real'+'imaginary'i' /* format as real+imaginaryi */

View file

@ -0,0 +1,2 @@
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])

View file

@ -0,0 +1,35 @@
program integerness(output);
{ determines whether a `complex` also fits in `integer` ---------------- }
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 ------------------------ }
function isIntegral(protected x: real): Boolean;
begin
isIntegral := isRealIntegral(cmplx(x * 1.0, 0.0))
end;
{ Rosetta code test ---------------------------------------------------- }
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.

View file

@ -0,0 +1,16 @@
use Math::Complex;
sub is_int {
my $number = shift;
if (ref $number eq 'Math::Complex') {
return 0 if $number->Im != 0;
$number = $number->Re;
}
return int($number) == $number;
}
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");
}

View file

@ -0,0 +1,4 @@
-->
<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>
<!--

View file

@ -0,0 +1,4 @@
-->
<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>
<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>
<!--

View file

@ -0,0 +1,4 @@
-->
<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>
<!--

View file

@ -0,0 +1,3 @@
-->
<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>
<!--

View file

@ -0,0 +1,4 @@
-->
<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>
<!--

View file

@ -0,0 +1,14 @@
(de int? (N)
(= N (* 1.0 (/ N 1.0)))) #returns T or NIL
(de integer? (N)
(and (= N (* 1.0 (/ N 1.0))) N)) #returns value of N or NIL
(scl 4) #-> 4 # *Scl the global which holds
1.0 #-> 10000
(int? 1.0) #-> T
(int? 1) #-> NIL # 1 with a scale of 4 is same as 0.0001 which is not an Integer
(int? -1.0) #-> T
(int? -0.0) #-> T
(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

View file

@ -0,0 +1,20 @@
function Test-Integer ($Number)
{
try
{
$Number = [System.Numerics.Complex]$Number
if (($Number.Real -eq [int]$Number.Real) -and ($Number.Imaginary -eq 0))
{
return $true
}
else
{
return $false
}
}
catch
{
Write-Host "Parameter was not a number."
}
}

View file

@ -0,0 +1,5 @@
Test-Integer 9
Test-Integer 9.9
Test-Integer (New-Object System.Numerics.Complex(14,0))
Test-Integer (New-Object System.Numerics.Complex(14,56))
Test-Integer "abc"

View file

@ -0,0 +1,26 @@
>>> def isint(f):
return complex(f).imag == 0 and complex(f).real.is_integer()
>>> [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]
>>> # Test cases
...
>>> isint(25.000000)
True
>>> isint(24.999999)
False
>>> isint(25.000100)
False
>>> isint(-2.1e120)
True
>>> isint(-5e-2)
False
>>> isint(float('nan'))
False
>>> isint(float('inf'))
False
>>> isint(5.0+0.0j)
True
>>> isint(5-5j)
False

View file

@ -0,0 +1,6 @@
[ $ "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 )

View file

@ -0,0 +1,88 @@
/* REXX ---------------------------------------------------------------
* 20.06.2014 Walter Pachl
* 22.06.2014 WP add complex numbers such as 13-12j etc.
* (using 13e-12 or so is not (yet) supported)
*--------------------------------------------------------------------*/
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 '1.000-3i'
Call test_integer '1.000-3.3i'
Call test_integer '4j'
Call test_integer '2.00000000+0j'
Call test_integer '0j'
Call test_integer '333'
Call test_integer '-1-i'
Call test_integer '1+i'
Call test_integer '.00i'
Call test_integer 'j'
Call test_integer '0003-00.0j'
Exit
test_integer:
Parse Arg xx
Numeric Digits 1000
Parse Value parse_number(xx) With x imag
If imag<>0 Then Do
Say left(xx,13) 'is not an integer (imaginary part is not zero)'
Return
End
Select
When datatype(x)<>'NUM' Then
Say left(xx,13) 'is not an integer (not even a number)'
Otherwise Do
If datatype(x,'W') Then
Say left(xx,13) 'is an integer'
Else
Say left(xx,13) 'isn''t an integer'
End
End
Return
parse_number: Procedure
Parse Upper Arg x
x=translate(x,'I','J')
If pos('I',x)>0 Then Do
pi=verify(x,'+-','M')
Select
When pi>1 Then Do
real=left(x,pi-1)
imag=substr(x,pi)
End
When pi=0 Then Do
real=0
imag=x
End
Otherwise /*pi=1*/Do
p2=verify(substr(x,2),'+-','M')
If p2>0 Then Do
real=left(x,p2)
imag=substr(x,p2+1)
End
Else Do
real=0
imag=x
End
End
End
End
Else Do
real=x
imag='0I'
End
pi=verify(imag,'+-','M')
If pi=0 Then Do
Parse Var imag imag_v 'I'
imag_sign='+'
End
Else
Parse Var imag imag_sign 2 imag_v 'I'
If imag_v='' Then
imag_v=1
imag=imag_sign||imag_v
Return real imag

View file

@ -0,0 +1,24 @@
/* 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

View file

@ -0,0 +1,50 @@
/*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.*/
if #s='' then #s= '3.14 1.00000 33 999999999 99999999999 1e272 AA 0' ,
'1.000-3i 1.000-3.3i 4j 2.00000000+0j 0j 333 -1-i' ,
'1+i .00i j 0003-00.0j 1.2d1 2e55666 +0003-00.0j +0j' ,
'-.3q+2 -0i +03.0e+01+0.00e+20j -030.0e-001+0.0e-020j'
/* [↑] use these numbers for defaults.*/
do j=1 for words(#s); ox=word(#s, j) /*obtain a number from the numbers list*/
parse upper var ox x /*obtain an uppercase version of OX. */
x=translate(x, 'EEI', "QDJ") /*translate exponent and imag indicator*/
if right(x, 1)=='I' then call tImag /*has the X number an imaginary part?*/
if isInt(x) then say right(ox, 55) " is an integer." /*yuppers, it does. */
else say right(ox, 55) " isn't an integer." /*noppers, it doesn't*/
end /*j*/ /* [↑] process each number in the list*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isInt: procedure; parse arg n /*obtain the number in question. */
if datatype(n, 'Whole') then return 1 /*it's a simple integer (small). */
parse var n m 'E' p /*separate base from the 10's power. */
if \datatype(p, 'Numb') then return 0 /*Not an integer if P not an integer.*/
return p>0 | m=0 /*is power>0 or mantissa = zero? */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isSign: parse arg ? 2; return ?=='+' | ?=="-" /*a method to test for a leading sign. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
tImag: x=left(x, length(x) -1) /*strip the trailing I or J from number*/
if isInt(x) then do /*is what's remaining an integer ? */
if x\=0 then x=. /*what's remaining isn't equal to zero.*/
return /*return to invoker in either case. */
end /* [↑] handle simple imaginary case. */
if isSign(x) then x=substr(x, 2) /*X has a sign? Strip the leading sign*/
e=verify(x, .0123456789) /*find 1st char not a digit or a dot. */
if e==0 then do; x=.; return; end /*Nothing? Then it's not an integer. */
y=substr(x, e, 1) /*Y is the suspect character. */
if isSign(y) then do /*is suspect character a plus or minus?*/
z=substr(x, e+1) /*obtain the imaginary part of X. */
x= left(x, e-1) /* " " real " " " */
if isInt(z) then if z=0 then return /*imaginary part is 0*/
x=. /*the imaginary part isn't zero. */
end /* [↑] end of imaginary part of X. */
if y\=='E' then return /*real part of X doesn't have an expon.*/
p=substr(x, e+1) /*obtain power of real part of X. */
_= left(p, 1) /*obtain the possible sign of the power*/
if isSign(_) then p=substr(p, 2) /*strip the sign from the exponent. */
s=verify(p, '-+', "M") /*is there an imaginary separator char?*/
if s==0 then do; x=.; return; end /*No sign? Then isn't not an integer.*/
z=substr(p, s+1) /*obtain the the imaginary part of X. */
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. */

View file

@ -0,0 +1,59 @@
/*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.*/
unaA= '+ + - -' /*" " " translated " " */
parse arg #s /*obtain optional numbers list from CL.*/
if #s='' then #s= '245+-00.0e-12i 245++++++0e+12j --3450d-1----0.0d-1j' ,
'4.5e11111222223333344444555556666677777888889999900'
/* [↑] use these numbers for defaults.*/
do j=1 for words(#s); ox=word(#s, j) /*obtain a number from the numbers list*/
parse upper var ox x /*obtain an uppercase version of OX. */
x=translate(x, 'EEJ', "QDI") /*translate exponent and imag indicator*/
do k=1 for words(unaB) /*process every possible unary operator*/
_=word(unaB, k) /*a unary operator to be changed, maybe*/
do while pos(_, x) \== 0 /*keep changing until no more are left.*/
x=changestr(_, x, word(unaA, k) ) /*reduce all unary operators (if any).*/
end /*while*/
end /*k*/
if right(x, 1)=='J' then call tImag /*has the X number an imaginary part?*/
if isInt(x) then say right(ox, 55) " is an integer." /*yuppers, it does. */
else say right(ox, 55) " isn't an integer." /*noppers, it doesn't*/
end /*j*/ /* [↑] process each number in the list*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isInt: procedure; parse arg n /*obtain the number in question. */
if datatype(n, 'Whole') then return 1 /*it's a simple integer (small). */
parse var n m 'E' p /*separate base from the 10's power. */
if \datatype(p, 'Numb') then return 0 /*Not an integer if P not an integer.*/
return p>0 | m=0 /*is power>0 or mantissa = zero? */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isSign: parse arg ? 2; return ?=='+' | ?=="-" /*a method to test for a leading sign. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
tImag: x=left(x, length(x) -1) /*strip the trailing I or J from number*/
if isInt(x) then do /*is what's remaining an integer ? */
if x\=0 then x=. /*what's remaining isn't equal to zero.*/
return /*return to invoker in either case. */
end /* [↑] handle simple imaginary case. */
if isSign(x) then x=substr(x, 2) /*X has a sign? Strip the leading sign*/
e=verify(x, .0123456789) /*find 1st char not a digit or a dot. */
if e==0 then do; x=.; return; end /*Nothing? Then it's not an integer. */
y=substr(x, e, 1) /*Y is the suspect character. */
if isSign(y) then do /*is suspect character a plus or minus?*/
z=substr(x, e+1) /*obtain the imaginary part of X. */
x= left(x, e-1) /* " " real " " " */
if isInt(z) then if z=0 then return /*imaginary part is 0*/
x=. /*the imaginary part isn't zero. */
end /* [↑] end of imaginary part of X. */
if y\=='E' then return /*real part of X doesn't have an expon.*/
p=substr(x, e+1) /*obtain power of real part of X. */
_= left(p, 1) /*obtain the possible sign of the power*/
if isSign(_) then p=substr(p, 2) /*strip the sign from the exponent. */
s=verify(p, '-+', "M") /*is there an imaginary separator char?*/
if s==0 then do; x=.; return; end /*No sign? Then isn't not an integer.*/
z=substr(p, s+1) /*obtain the the imaginary part of X. */
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. */

View file

@ -0,0 +1,52 @@
#lang racket
(require tests/eli-tester)
(test ;; known representations of integers:
;; - as exacts
(integer? -1) => #t
(integer? 0) => #t
(integer? 1) => #t
(integer? 1234879378539875943875937598379587539875498792424323432432343242423432432) => #t
(integer? -1234879378539875943875937598379587539875498792424323432432343242423432432) => #t
(integer? #xff) => #t
;; - as inexacts
(integer? -1.) => #t
(integer? 0.) => #t
(integer? 1.) => #t
(integer? 1234879378539875943875937598379587539875498792424323432432343242423432432.) => #t
(integer? #xff.0) => #t
;; - but without a decimal fractional part
(integer? -1.1) => #f
;; - fractional representation
(integer? -42/3) => #t
(integer? 0/1) => #t
(integer? 27/9) => #t
(integer? #xff/f) => #t
(integer? #b11111111/1111) => #t
;; - but obviously not fractions
(integer? 5/7) => #f
; - as scientific
(integer? 1.23e2) => #t
(integer? 1.23e120) => #t
; - but not with a small exponent
(integer? 1.23e1) => #f
; - complex representations with 0 imaginary component
; is a subset of the sets of rational and /real/ numbers and
(integer? 1+0i) => #t
(integer? (sqr 0+1i)) => #t
(integer? 0+1i) => #f
;; oh, there's so much else that isn't an integer:
(integer? "woo") => #f
(integer? "100") => #f
(integer? (string->number "22/11")) => #t ; just cast it!
(integer? +inf.0) => #f
(integer? -inf.0) => #f
(integer? +nan.0) => #f ; duh! it's not even a number!
(integer? -NaN.0) => #f
(integer? pi) => #f
)

View file

@ -0,0 +1,17 @@
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>);
}

View file

@ -0,0 +1,13 @@
class Numeric
def to_i?
self == self.to_i rescue false
end
end
# Demo
ar = [25.000000, 24.999999, 25.000100, -2.1e120, -5e-2, # Floats
Float::NAN, Float::INFINITY, # more Floats
2r, 2.5r, # Rationals
2+0i, 2+0.0i, 5-5i] # Complexes
ar.each{|num| puts "#{num} integer? #{num.to_i?}" }

View file

@ -0,0 +1,10 @@
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))
}

View file

@ -0,0 +1,7 @@
proc isNumberIntegral {x} {
expr {$x == entier($x)}
}
# test with various kinds of numbers:
foreach x {1e100 3.14 7 1.000000000000001 1000000000000000000000 -22.7 -123.000} {
puts [format "%s: %s" $x [expr {[isNumberIntegral $x] ? "yes" : "no"}]]
}

View file

@ -0,0 +1,8 @@
% set a 1.0000000000000001
1.0000000000000001
% expr $a
1.0
% IsNumberIntegral $a
1
% puts $a
1.0000000000000001

View file

@ -0,0 +1,5 @@
>>> a = 1.0000000000000001
>>> a
1.0
>>> 1.0 == 1.0000000000000001
True

View file

@ -0,0 +1,37 @@
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)
}

View file

@ -0,0 +1,9 @@
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.;
]

View file

@ -0,0 +1 @@
T(1, 2.0,4.1,"nope",self).apply((1).isType)

View file

@ -0,0 +1,3 @@
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);