The problem of float accuracy in C language

Source: Internet
Author: User

3.1415926 (10 binary) = =

11.00100100001111110110100110100010010110110000100101 (2 binary) = =

1.100100100001111110110100110100010010110110000100101 * 2


Debug print with GdB the contents of the float variable are 0X40490FDA (16 binary), i.e. 01000000010010010000111111011010 (2 binary)

0 (Highest bit 0, indicates positive number) 10000000 (IEEE stipulates that the sub-square to be calculated here is the true exponent minus 127, where the exponent is 1) 10010010000111111011010 (this 23 bit represents the fractional part,

Because the hidden bit technology is used in the computer: the highest bit of 1 does not write memory, so the fractional part is actually 1.10010010000111111011010)

1.10010010000111111011010 (2 binary) ==1.5707962512969970703125 (10 binary)

1.5707962512969970703125 * 2 = = 3.141592502593994140625

float F = 3.1415926;

printf ("%f\n", f);

The printf function defaults to the decimal 6 bits, and the last one is rounded, so the result is 3.141593.

The following is validation:

printf ("%.7f\n", f); The result should be 3.1415925;

printf ("%.8f\n", f); The result should be 3.14159250.

printf ("%.9f\n", f); The result should be 3.141592503.



Because the mantissa of float is 23 bits, the decimal place retains 23 bits, i.e.

3.1415926 (10 binary) = = 1.1001001000011111101100 (2 binary)


Because the hidden bit technology is used in the computer: the highest bit of 1 does not write memory, so 1.1001001000011111101100 (2 binary) should be represented as 0.1001001000011111101100


Because the index can be negative, in order to facilitate the calculation, so the IEEE stipulates that the sub-square to be calculated here to subtract 127 is the true exponent, where the exponent is 1 (that is, 2 of the 1 power)

The problem of float accuracy in C language

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.