Test integerness: Difference between revisions

Content added Content deleted
No edit summary
(expanded example for clarity, added more tests)
Line 858: Line 858:


=={{header|Tcl}}==
=={{header|Tcl}}==

{{incomplete}}
The simplest method of doing this is testing whether the value is equal to the value after casting it to a integral value.
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).

<lang tcl>proc isNumberIntegral {x} {
<lang tcl>proc isNumberIntegral {x} {
expr {$x == entier($x)}
expr {$x == entier($x)}
}
}
# test with various kinds of numbers:
foreach x {3.14 7 1000000000000000000000} {
foreach x {1e100 3.14 7 1.000000000000001 1000000000000000000000 -22.7 -123.000} {
puts [format "%s: %s" $x [expr {[isNumberIntegral $x] ? "yes" : "no"}]]
puts [format "%s: %s" $x [expr {[isNumberIntegral $x] ? "yes" : "no"}]]
}</lang>
}</lang>
{{out}}
{{out}}
<pre>
<pre>
1e100: yes
3.14: no
3.14: no
7: yes
7: yes
1.000000000000001: no
1000000000000000000000: yes
1000000000000000000000: yes
-22.7: no
-123.000: yes
</pre>
</pre>

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:

<lang Tcl>% set a 1.0000000000000001
1.0000000000000001
% expr $a
1.0
% IsNumberIntegral $a
1
% puts $a
1.0000000000000001</lang>

compare Python:

<lang Python>>>> a = 1.0000000000000001
>>> a
1.0
>>> 1.0 == 1.0000000000000001
True</lang>

.. this is a fairly benign illustration of why comparing floating point values with == is usually a bad idea.


=={{header|zkl}}==
=={{header|zkl}}==