For a plot program under construction, I had to test whether a ratio of two numbers yielded an integer or not.

The test can easily be done with accompanying "Odd (n)" and "Even (n)" functions because both functions regard non-integers as "False".

The problem is caused by quantization errors in the calculation that cause inaccuracies in the order of magnitude of 1E-16.

My solution is the function "Crop (n, digits)" that the mantissa of 'n' shorten to 'digits' numbers.

The accompanying code is a test program:

Code: Select all

```
'Integer test on number ratio
'by Ton Nillesen, October 2019
'
OPTION TAB 15
D=0.5
PRINT "D =";D
PRINT " I"," I/D","Odd+Even"
FOR i=-0.02 TO 0.085 STEP 0.005
R=Crop(i/d,3) ' trim mantissa to 9 significant digits
'R=i/d ' comment or uncomment this for good or wrong results
PRINT i,r,ODD(r)+EVEN(r)
NEXT i
END
'
DEF Crop(n,digits)
'trim mantissa of 'n' to 'digits' numbers
IF ABS(n)<10^(-digits) THEN RETURN 0
'--- normalise
pwr=CEIL(LOG10(ABS(n)))
n*=1/10^pwr
'--- round
m=10^digits
n=INT(m*n+0.5)/m
'--- restore
n*=10^pwr
RETURN n
END DEF
'
DEF Even(n)
'returns 0 if n is non-integer or n is even
'else returnvalue is 1
IF (ABS(n)-INT(ABS(n)))>0 THEN RETURN 0
IF INT(n/2)=n/2 THEN RETURN 1 ELSE RETURN 0
END DEF
```

The following result is with usage of the crop function

Code: Select all

```
D = 0.5
I I/D Odd+Even
-2.2 -4.4 0
-2 -4 1
-1.8 -3.6 0
-1.6 -3.2 0
-1.4 -2.8 0
-1.2 -2.4 0
-1 -2 1
-0.8 -1.6 0
-0.6 -1.2 0
-0.4 -0.8 0
-0.2 -0.4 0
-2.77556E-16 -5.55112E-16 0
0.2 0.4 0
0.4 0.8 0
0.6 1.2 0
0.8 1.6 0
1 2 1
1.2 2.4 0
1.4 2.8 0
1.6 3.2 0
1.8 3.6 0
2 4 1
2.2 4.4 0
```

The values -2.77556E-16 and -5.55112E-16 where both should be 0 have led me to the solution.

The following wrong result is without using the Crop function.

Code: Select all

```
D = 0.5
I I/D Odd+Even
-2.2 -4.4 0
-2 -4 1
-1.8 -3.6 0
-1.6 -3.2 0
-1.4 -2.8 0
-1.2 -2.4 0
-1 -2 0
-0.8 -1.6 0
-0.6 -1.2 0
-0.4 -0.8 0
-0.2 -0.4 0
-2.77556E-16 -5.55112E-16 0
0.2 0.4 0
0.4 0.8 0
0.6 1.2 0
0.8 1.6 0
1 2 0
1.2 2.4 0
1.4 2.8 0
1.6 3.2 0
1.8 3.6 0
2 4 0
2.2 4.4 0
```