Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to use -DBL_MAX in code?

Tags:

c++

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.

like image 685
EmptyData Avatar asked Feb 25 '13 10:02

EmptyData


People also ask

Is it safe to use VS Code?

Visual Studio Code takes security seriously and wants to help you safely browse and edit code no matter the source or original authors. The Workspace Trust feature lets you decide whether code in your project folder can be executed by VS Code and extensions without your explicit approval.

Is code :: block safe?

Despite the vulnerability that was found in 2020, Code Blocks is still safe to use and doesn't present any major security flaws. With more than 1.3 billion viruses in circulation ensuring the software you use is safe is vital.

Why do people use code?

Coding is used for communicating with computers. People use coding to give computers and other machines instructions on what actions to perform. We also use computer code to program the websites, apps, and other technologies we interact with every day.


1 Answers

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;
like image 91
Cheers and hth. - Alf Avatar answered Sep 20 '22 17:09

Cheers and hth. - Alf