The maximum value of type float and the actual available value

Source: Internet
Author: User

Some time ago to hit the code found something about the type of float strange phenomenon, take it out and share with you.

Run the following code on Linux:

#include <stdio.h>
int main () {
float a=16777216;
float b=16777217;
float c=16777218;
float d=16777219;
float e=16777220;

printf ("a=%f\n", a);
printf ("b=%f\n", b);
printf ("c=%f\n", c);
printf ("d=%f\n", D);
printf ("e=%f\n", e);

return 0;
}

Results:

a=16777216.000000
b=16777216.000000
c=16777218.000000
d=16777220.000000
e=16777220.000000
Did you find out: The results are not output 16777217 and 16777219!

In fact, according to the IEEE754 Standard, a 32-bit binary floating-point number can be represented as consisting of a sign bit s, eight-bit exponent bits e ' and 23-bit decimal bits m.

As a general rule, the maximum value for a float type should be 1.111 ... X 2^127 (2^8-127). Far beyond the value of 16777216.

But in fact the index is so large and the mantissa is not necessarily so large, the mantissa is the largest 2^24=16777216. Which means that when you use float for 16777217,

, in fact, the most right one is discarded, can only represent the number of the left 24 digits. But 16777218 different, it's the right one is 0, the last one is truncated and no shadow

Only need to add an index to the line. That is, after the value of float is greater than 16777216 so, although the maximum value of float type is 2^127, but due to the mantissa limit, many float type number in more than 16777216

is not to be expressed.

The maximum value of type float and the actual available value

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.