Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is 'const' double copying + comparison safe?

I've noticed there's a lot of discussion on the topic of floating-point computation errors which require you to use more complex comparison than ==. However, all those articles seem to be assuming the value is manipulated (or double-calculated) somehow, while I didn't see an example covering a very simple constant copying.

Please consider the following:

const double magical_value = -10;

class Test
{
    double _val;

public:
    Test()
        : _val(magical_value)
    {
    }

    bool is_special()
    {
        return _val == magical_value;
    }
};

As far as I understand this, magical_value should be set at compile time, so that all rounding occurs at that point. Afterwards, the value should just be copied to the class, and compared with the original one. Is such a comparison guaranteed to be safe? Or can either copying or comparing introduce errors here?

Please do not suggest alternative comparison or magical value use methods, that's another topic. I'm just curious about this assumption.

Edit: just to note, I am a little afraid that on some architectures, the optimizations could result in copying the value to a differently-sized floating-point registers, thus introducing differences in the exact values. Is there a risk of something like that?

like image 599
Michał Górny Avatar asked Jun 13 '12 08:06

Michał Górny


People also ask

What is double const?

Declaring a variable to be const means that its value cannot change; therefore it must be given a value in its declaration: const double TEMP = 98.6; // TEMP is a const double. ( Equivalent: double const TEMP = 98.6; )

What is mean const in c++?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.


1 Answers

Is such a comparison guaranteed to be safe? Or can either copying or comparing introduce errors here?

Yes, safe (this is a requirement of the copy operation as implied by =). There are no conversions/promotions that you need to worry about as long as the source and destination types are same.

However, note that magical_value may not contain 10 exactly but an approximation. This approximation will get copied over to _val.

Given the const qualifier, chances are that magical_value will probably be optimized away (should you turn on optimizations) or used as-is (i.e. no memory will probably be used up).

like image 143
dirkgently Avatar answered Sep 25 '22 06:09

dirkgently