简体   繁体   English

为什么浮点数打印为负零?

[英]Why does a float print out as negative zero?

Problem 问题

Sometimes the floating point number of value zero is being printed out as negative zero even though inequality checks show that the number is non-negative. 有时,即使不等式检查显示该数字为非负数,零值的浮点数也会被打印为负零。

Application 应用

I'm trying to log out the transformation matrix of a UIView in a human readable format. 我正在尝试以人类可读的格式注销UIView的转换矩阵。 The numbers should be arranged like this: 数字应按以下方式排列:

在此处输入图片说明

- (void) describe
{
    NSLog(
        @"|%@%.2f %@%.2f 0.00|\n|%@%.2f %@%.2f 0.00|\n|%@%.2f %@%.2f 1.00|",
        self.transform.a < 0 ? @"" : @" ",
        self.transform.a,
        self.transform.b < 0 ? @"" : @" ",
        self.transform.b,
        self.transform.c < 0 ? @"" : @" ",
        self.transform.c,
        self.transform.d < 0 ? @"" : @" ",
        self.transform.d,
        self.transform.tx < 0 ? @"" : @" ",
        self.transform.tx,
        self.transform.ty < 0 ? @"" : @" ",
        self.transform.ty
    );
}

I place spaces in front of numbers that are non-negative to match the width of negative numbers. 我在非负数前面放置空格以匹配负数的宽度。 In some cases, the numbers line up: 在某些情况下,数字会对齐:

| 0.00 -1.00 0.00|
| 1.00  0.00 0.00|
| 0.00  0.00 1.00|

After applying a few rotations to the view, the numbers don't line up anymore: 对视图进行几次旋转后,数字不再对齐:

| -0.00 -1.00 0.00|
| 1.00  -0.00 0.00|
| 0.00  0.00 1.00|

In the above case, an NSLog of self prints out the transform as: 在上述情况下,一个selfNSLog将转换输出为:

transform = [-0, -1, 1, -0, 0, 0];

The problem is zero values are logged out as negative zero, but being detected as non-negative. 问题是零值被注销为负零,但被检测为非负。 If I can understand how this mythical negative zero can even exist, then I can solve my formatting problem. 如果我能理解这个神话般的负零甚至可以存在,那么我就可以解决格式问题。

[Answer moved from comment] [答案转为评论]

floating point values have mantisa,exponent and sign separate 浮点值的螳螂值,指数和符号分开

  • so they are capable of storing +0 and -0 which is the same ... 因此它们能够存储+0和-0,这是相同的...
  • the sign is leftover from last operation with such value ... 该符号是从上次操作留下来的,具有这样的值...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM