Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Platform-independent way to obtain maximum C++ float value

What’s the best, platform-independent way to obtain the maximum value that can be stored in a float in C++?

like image 826
Tony the Pony Avatar asked Sep 27 '09 19:09

Tony the Pony


People also ask

What is the maximum value of float in C?

This representation gives a range of approximately 3.4E-38 to 3.4E+38 for type float. You can declare variables as float or double, depending on the needs of your application.

What is the maximum float value?

What will be maximum size of a float variable? A signed 32-bit integer variable has a maximum value of 231 − 1 = 2,147,483,647, whereas an IEEE 754 32-bit base-2 floating-point variable has a maximum value of (2 − 2−23) × 2127 ≈ 3.4028235 × 1038.

Is C++ float 32 or 64?

Difference between float and double in C/C++ float is a 32-bit IEEE 754 single precision Floating Point Number – 1 bit for the sign, 8 bits for the exponent, and 23* for the value.

What does float H do in C?

The header float. h contains macros that expand to various limits and parameters of the standard floating-point types. The macros, as defined on ISO 9899:1999 section 5.2.


4 Answers

std::numeric_limits    

like image 97
Georg Fritzsche Avatar answered Sep 24 '22 02:09

Georg Fritzsche


std::numeric_limits<float>::max()
like image 32
hrnt Avatar answered Sep 22 '22 02:09

hrnt


std::numeric_limits

// numeric_limits example
#include <iostream>
#include <limits>
using namespace std;

int main () {

  cout << "Minimum value for float: " << numeric_limits<float>::min() << endl;
  cout << "Maximum value for float: " << numeric_limits<float>::max() << endl;
  cout << "Minimum value for double: " << numeric_limits<double>::min() << endl;
  cout << "Maximum value for double: " << numeric_limits<double>::max() << endl;
  return 0;
}
like image 40
Todd Avatar answered Sep 24 '22 02:09

Todd


In C++ you can use the std::numeric_limits class to get this sort of information.

If has_infinity is true (which will be true for basically all platforms nowadays), then you can use infinitity to get the value which is greater than or equal to all other values (except NaNs). Similarly, its negation will give a negative infinity, and be less than or equal to all other values (except NaNs again).

If you want finite values, then you can use min/max (which will be less than or equal to/greater than or equal to all other finite values).

like image 34
Simon Byrne Avatar answered Sep 26 '22 02:09

Simon Byrne