8

I want extreme -ve value .

#include <iostream> 
using namespace std; 
#include <math.h>
#include <limits.h>
#include <values.h>

#define THRESHOLD 2*DBL_MIN

#define FEQ(x, y) (fabs((x) - (y)) < THRESHOLD)

int main( )
{ 
double  a = -DBL_MAX; // I want here minimum value of double
if(FEQ(a,-DBL_MAX))
cout<<"Equal " <<endl;
else
cout<<"NOt equal"<<endl;
return 0;



}

So , is it safe to use -DBL_MAX in code? If anybody know better approach please share here.

EmptyData
  • 2,386
  • 2
  • 26
  • 42
  • 11
    @MarounMaroun `-DBL_MAX != DBL_MIN` – user703016 Feb 25 '13 at 10:09
  • 2
    I recommend using [`std::numeric_limits`](http://en.cppreference.com/w/cpp/types/numeric_limits) instead of the old C macros. – Some programmer dude Feb 25 '13 at 10:10
  • 6
    @MarounMaroun: [`std::numeric_limits::min()` (which is equal to `DBL_MIN`)](http://en.cppreference.com/w/cpp/types/numeric_limits/min) is a positive value (after all, we're talking about floating points, so there must be some quirk). Now with C++11 one can simply use [`std::numeric_limits::lowest()`](http://en.cppreference.com/w/cpp/types/numeric_limits/lowest) (which evaluates to `-DBL_MAX`. – Zeta Feb 25 '13 at 10:20
  • Note that for IEEE representations (and in general any *floating*-point math), the only way that `fabs(a - -DBL_MAX)` can be less than `2*DBL_MIN` is if `a + DBL_MAX` is 0. Think about the precision (i.e. the number of bits in the significand), there is no value of `double` that lies between `-DBL_MAX` and the number mathematically equal to `-DBL_MAX` plus twice `DBL_MIN`. So what you're doing here is a long-winded version of `a == -DBL_MAX`. – Steve Jessop Feb 25 '13 at 11:29
  • 1
    This question has been answered before. [Here.](http://stackoverflow.com/questions/1153548/minimum-double-value-in-c-c) by [dfa](http://stackoverflow.com/users/89266/dfa). – Alex Feb 25 '13 at 10:21

1 Answers1

9

DBL_MAX is part of the standard library. As such it's not particularly unsafe.

However, comparing non-integral floating point values for equality is inherently unsafe, in the sense of unreliable.

That's because floating point arithmetic may be performed with higher precision than your chosen type, with results converted back and forth, and not always as you'd think.


in passing, defining a macro like:

#define FEQ(x, y) (fabs((x) - (y)) < THRESHOLD)

… is unsafe: you can easily become victim of undesired text substitution and besides it's an eyesore.

Instead use an inline function, even if inline does not guarantee optimization:

inline bool feq( double const x, double const y ) { return fabs( x - y ) < THRESHOLD; }

and then the same goes for the constant THRESHOLD, it should simply be a constant in C++:

double const threshold = 2*DBL_MIN;
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331