Test integerness: Difference between revisions

expanded example for clarity, added more tests
No edit summary
(expanded example for clarity, added more tests)
Line 858:
 
=={{header|Tcl}}==
 
{{incomplete}}
The simplest method of doing thisway is testingto test whether the value is (numerically) equal to theitself valuecast afteras castingan itinteger. to aentier() integralperforms valuethis cast without imposing any word-size limits (as int() or wide() would).
 
<lang tcl>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"}]]
}</lang>
{{out}}
<pre>
1e100: yes
3.14: no
7: yes
1.000000000000001: no
1000000000000000000000: yes
-22.7: no
-123.000: yes
</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}}==
Anonymous user