Reputation: 488
I'm trying to find the minimum (positive) value (closest to zero) that I can store in a single precission floating point number. Using the <limits>
header I can get the value, but if I make it much smaller, the float can still hold it and it gives the right result. Here is a test program, compiled with g++ 5.3.0.
#include <limits>
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
float a = numeric_limits<float>::max();
float b = numeric_limits<float>::min();
a = a*2;
b = b/pow(2,23);
cout << a << endl;
cout << b << endl;
}
As I expected, "a" gives infinity, but "b" keeps holding the good result even after dividing the minimum value by 2^23, after that it gives 0.
The value that gives numeric_limits<float>::min()
is 2^(-126) which I belive is the correct answer, but why is the float on my progam holding such small numbers?
Upvotes: 7
Views: 11210
Reputation: 19761
I'm trying to find the minimum value (closest to zero) that I can store in a single precission floating point number
0 is the closest value to 0 that you can store in any precision float. In fact, you can store it two ways, as there is a positive and negative 0.
edit: I edited the question to specify positive but this was the correct answer for what was originally asked.
Upvotes: -4
Reputation: 76305
std::numeric_limits::min
for floating-point types gives the smallest non-zero value that can be represented without loss of precision. std::numeric_limits::lowest
gives the smallest representable value. With IEEE representations that's a subnormal value (previously called denormalized).
Upvotes: 7
Reputation: 214
From wikipedia https://en.wikipedia.org/wiki/Single-precision_floating-point_format:
The minimum positive normal value is 2^−126 ≈ 1.18 × 10^−38 and the minimum positive (denormal) value is 2^−149 ≈ 1.4 × 10^−45.
So, for
cout << (float)pow(2,-149)
<< "-->" << (float)pow(2,-150)
<< "-->" << (float)pow(2,-151) << endl;
I'm getting:
1.4013e-45-->0-->0
Upvotes: 3