在Tcl中打印负零的解决方法

huangapple go评论58阅读模式
英文:

Work arounds to printing negative zero in tcl

问题

我正在重新编写脚本的一部分,以在tcl中执行,因为有一个只能在tcl中使用的工具。在这段代码中,用户可以提供一个选项(-m用于镜像),以便将值沿y轴翻转。(基本上,所有x值都会乘以-1。)当打印出从这个翻转中得到的值时,我意识到我的输出中在原始脚本中有0.0000的地方有-0.0000。

我通过以下方式解决了这个问题:

if {$mirrored eq "t" && $text_x != 0} {
    # 在tcl中,如果将0乘以-1,将得到-0,我们不希望出现这种情况
    set text_x [expr {$text_x * -1.0}]
}

我对这个解决方案感到满意,但在我的if语句中包含这个特殊情况感觉有点奇怪。是否有更简洁、优雅或被接受的方法来做到这一点?或者其他任何方式吗?

英文:

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?

答案1

得分: 3

Add zero:

复制您所述的行为:

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

以及解决方法:

% 设置 z [expr {$x * -1.0 + 0}]
0.0
英文:

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

答案2

得分: 0

是的,这个有点奇怪。我不知道Tcl为什么这样做。一个解决方法是简单地从零减去text_x

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

一些例子:

% 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
英文:

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

huangapple
  • 本文由 发表于 2023年7月18日 05:01:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76708047.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定