C++ – How to calculate the range of data type float in c++

cmathtype conversion

As we can see int has 4 byte in memory, that are 32bits, after applying range formula , we can see range of int -2147483648 to 2147483647. I have calculated the ranges of all datatypes besides float and double and long double.
I dont know how they calculated the range of float mentioned below.

Ranges of different datatypes in c++

Best Answer

Floating point numbers are stored as an exponent and a fraction within the space available.

For some systems where float is implemented as an IEEE 754 value, the results would looks as below.

sign : 1 bit
exponent : 8 bits
fraction : 23 bits

The exponent allows numbers from 2 ^ (-127) (2 to the power -127) to 2 ^ 128 ( 2 to the power 128).

Allowing a range of numbers from

5.87747E-39 3.40282E+38

the fraction point gives a fraction such as .12313

Thus with 23 bits of values, the accuracy of a number is about 7 decimal digits or 1.19 E-7

For more details see wikipedia : IEEE 754-1985

On a given system, the <cfloat> / <float.h> will give the limits. For non IEEE 754 based representations, you would have to understand how the numbers are stored to calculate the limits.