Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zero minus zero equivalent to infinity?

I'm writing a method that creates a copy of an array of arrays of floats. I was getting some extremely weird values after debugging this, so I thought I'd ask about this since I wasn't able to figure this out by reading about C++ array FAQs.

Here's the relevant parts of the code (it's part of an enormous program, with most of the stuff irrelevant for this post):

// height and width are integer global variables
void method () {
    float testArray[height][width];
    for(int j = 0; j < height; ++j) {
        for(int i = 0; i < width; ++i) {
            testArray[j][i] -= 0.0;
            std::cout << testArray[j][i] << std::endl;
        }
    }
}

(In my tests, height = 32 and width = 256, but that shouldn't be relevant.) When I initialize testArray, it's values should all be 0.0, correct? Then, in the loop, I subtract 0.0 from a certain element in testArray, which should logically not change the value at all. But printing the values of testArray as a debugging step result in some weird values, such as the following snippet:

[...]
0
[...]
-3.23805e-24
[...]
8.40779e-45
[...]
1.79513e+37
[...]
0
[...]
3.19586e+36
[...]

The most worrisome values are the infinite ones, such as the fourth number listed above. I honestly don't know why this is occurring. Shouldn't all these values still be approximately 0.0? I thought it had to do with imprecision of floating point arithmetic, but that shouldn't result in an infinite value ....

like image 351
TakeS Avatar asked Nov 19 '12 20:11

TakeS


2 Answers

Try initializing the values in the array:

float testArray[height][width] = {};
like image 26
David Rodríguez - dribeas Avatar answered Oct 14 '22 00:10

David Rodríguez - dribeas


No, when you declare your array like that it will be uninitialized since it's a builtin type. You'll need to initialize it to zero yourself before doing the subtraction.

But note that declaring an array as you have (with presumably non-const dimensions) is a compiler extension and not part of the language.

I would just use vector which solves both problems at once.

std::vector<std::vector<float> > testArray(height, std::vector<float>(width));
like image 104
Mark B Avatar answered Oct 14 '22 01:10

Mark B