I'm new to C++!
Wiki says this about float
: 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.
But if a float can have max 7 digit (≈ 7.225
), the min is it not just 0,0000001
? I'm confused :)
First of all you should know that 0.4 and 0.5 are double constants while 0.4f and 0.5f are floating point constants.
A single precision floating-point number is a short (32 bits) floating-point number. The range of single precision floating-point numbers is about -7.2E+75 to 7.2E+75. In this range, the largest negative value is about -5.4E-79, and the smallest positive value is about 5.4E-079.
The smallest representable positive number is 2−7 = 1/128 (bit pattern 00000000), and the largest representable negative number is −2−7 = −1/128 (bit pattern 10000000). These are small numbers, but when we look at the above number line, we see an anomaly: They're separated by a weirdly large gap.
And the reason the comparison succeeds with 1.5 is that 1.5 can be represented exactly as a float and as a double ; it has a bunch of zeros in its low bits, so when the promotion adds zeros the result is the same as the double representation.
A floating point number consists of 3 parts: a sign, a fraction, and an exponent. These are all integers, and they're combined to get a real number: (-1)sign × (fraction × 2-23) × 2exponent
The Wikipedia article uses a binary number with a decimal point for the fraction, but I find it clearer to think of it as an integer multiplied by a fixed constant. Mathematically it's the same.
The fraction is 23 bits, but there's an extra hidden bit that makes it a 24-bit value. The largest integer that can be represented in 24 bits is 16777215, which has just over 7 decimal digits. This defines the precision of the format.
The exponent is the magic that expands the range of the numbers beyond what the precision can hold. There are 8 bits to hold the exponent, but a couple of those values are special. The value 255 is reserved for infinities and Not-A-Number (NAN) representations, which aren't real numbers and don't follow the formula given above. The value 0 represents the denormal range, which are called that because the hidden bit of the fraction is 0 rather than 1 - it's not normalized. In this case the exponent is always -126
. Note that the precision of denormal numbers declines as the fraction gets smaller, because it has fewer digits. For all the other bit patterns 1-254, the hidden bit of the fraction is 1 and the exponent is bits-127
. You can see the details at the Wikipedia section on exponent encoding.
The smallest positive denormal number is (-1)0 × (1 × 2-23) × 2-126, or 1.4e-45.
The smallest positive normalized number is (-1)0 × (0x800000 × 2-23) × 2(1 - 127), or 1.175494e-38.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With