Test integerness: Difference between revisions

Content added Content deleted
(Updated to work with Nim 1.4: added parentheses around negative floats. Changed "is_integer" to "isInteger" to follow Nim guidelines. Done miscellaneous minor changes.)
Line 1,680: Line 1,680:
{{out}}<pre>{False,False,True,False}</pre>
{{out}}<pre>{False,False,True,False}</pre>
=={{header|Nim}}==
=={{header|Nim}}==
a taxonomy of Nim number types:
A taxonomy of Nim number types:


SomeInteger: integer types, signed or unsigned, 8,16,32,or 64 bits
::– SomeInteger: integer types, signed or unsigned, 8,16,32,or 64 bits


SomeFloat: floating point, 32 or 64 bits
::– SomeFloat: floating point, 32 or 64 bits


SomeNumber: SomeInteger or SomeFloat
::– SomeNumber: SomeInteger or SomeFloat


Rational: rational type; a numerator and denominator, of any (identical) SomeInteger type
::– Rational: rational type; a numerator and denominator, of any (identical) SomeInteger type


Complex: complex type; real and imaginary of any (identical) SomeFloat type
::– Complex: complex type; real and imaginary of any (identical) SomeFloat type


<lang nim>import complex, rationals, math, fenv, sugar
<lang nim>import complex, rationals, math, fenv, sugar

func is_integer[T:Complex | Rational | SomeNumber](x: T, tolerance: float64 = 0.0): bool =
func isInteger[T: Complex | Rational | SomeNumber](x: T; tolerance = 0f64): bool =
when T is Complex:
when T is Complex:
x.im == 0 and x.re.is_integer
x.im == 0 and x.re.isInteger
elif T is Rational:
elif T is Rational:
x.dup(reduce).den == 1
x.dup(reduce).den == 1
Line 1,703: Line 1,704:
true
true


# Floats.
assert not NaN.is_integer
assert not INF.is_integer #ceil(INF)-INF = NaN
assert not NaN.isInteger
assert not INF.isInteger # Indeed, "ceil(INF) - INF" is NaN.
assert not -5e-2.is_integer
assert -2.1e120.is_integer
assert not (-5e-2).isInteger
assert (25.0).is_integer
assert (-2.1e120).isInteger
assert not 24.999999.is_integer
assert 25.0.isInteger
assert 24.999999.is_integer(tolerance = 0.00001)
assert not 24.999999.isInteger
assert 24.999999.isInteger(tolerance = 0.00001)
assert not (1.0'f64 + epsilon(float64)).is_integer
assert not (1.0'f32 - epsilon(float32)).is_integer
assert not (1f64 + epsilon(float64)).isInteger
assert not (1f32 - epsilon(float32)).isInteger
#rationals
# Rationals.
assert not (5 // 3).is_integer
assert (9 // 3).is_integer
assert not (5 // 3).isInteger
assert (-143 // 13).is_integer
assert (9 // 3).isInteger
assert (-143 // 13).isInteger
#unsigned
# Unsigned integers.
assert (3'u).is_integer
assert 3u.isInteger
#complex
# Complex numbers.
assert not (1.0 + im 1.0).is_integer
assert (5.0 + im 0.0).is_integer</lang>
assert not (1.0 + im 1.0).isInteger
assert (5.0 + im 0.0).isInteger</lang>


=={{header|ooRexx}}==
=={{header|ooRexx}}==