Work arounds to printing negative zero in tcl

62 Views Asked by At

I'm dealing with rewriting a portion of a script to execute in a tcl because of a tool that's only available in tcl. In this code, the user can provide an option (-m for mirrored) to flip values around the y axis. (Basically, all the x values get multiplied by -1.) When printing out the values that resulted from this flipping, I realized that my output had a -0.0000 wherever the original script had 0.0000.

I fixed this issue by not multiplying the x value by -1 if it's equal to zero as bellow:

    if {$mirrored eq "t" && $text_x != 0} {
        #in tcl if you multiply 0 by -1 you get -0 we don't want that
        set text_x [expr {$text_x * -1.0}]
    }

I am okay with this solution, but it feels a bit weird to include this one case in my if statement. Is there a more concise, elegant or accepted way of doing this? Or any other way at all?

2

There are 2 best solutions below

0
glenn jackman On BEST ANSWER

Add zero:

Replicating your stated behaviour:

% set x 0
0
% set y [expr {$x * -1.0}]
-0.0

and the remedy

% set z [expr {$x * -1.0 + 0}]
0.0
1
TrojanName On

Yeah, it's a funny one. I don't know the reasons why Tcl does this. One solution is to simply subtract text_x from zero

if {$mirrored eq "t"} {
       set text_x [expr {0 - $text_x }]
}

Some examples:

% set text_x 0
0
% set text_x [expr {0 - $text_x }]
0
% set text_x 0.0
0.0
% set text_x [expr {0 - $text_x }]
0.0
% set text_x 1.2
1.2
% set text_x [expr {0 - $text_x }]
-1.2
% set text_x 15
15
% set text_x [expr {0 - $text_x }]
-15