0

I am using TCL 8.4 While the following works as expected,

% if { 50.02 < 50.02 } { puts HI }
% set s 50.02
50.02
% if { $s <  50.02 } { puts HI }
% set high 50.02
50.02
% if { $s <  $high } { puts HI }
%
%
% if { 50.02 < $high } { puts HI }

Why this following does not work ? I really cannot understand this behavior. Note : when $s is 50.03, it works as expected.

% set s [ expr 50.01 + 0.01 ]
50.02
% if { $s <  $high } { puts HI }
HI
% set s [ expr double(50.01 + 0.01) ]
50.02
% if { $s <  $high } { puts HI }
HI

1 Answers1

0

Floating point numbers cannot be stored precisely. For two numbers which mathematically are supposed to be equal, the comparison result may be incorrect.

My Tcl 8.6 prints (and that may explain the result you get):

% set s [ expr 50.01 + 0.01 ]
50.019999999999996

More details about this are available at wiki.tcl.tk: A real problem

nnn
  • 3,980
  • 1
  • 13
  • 17