Floating-point traps

Source: Internet
Author: User

1#include <stdio.h>2 intMain ()3 {4     Doublei;5      for(i =0.0; I! =Ten; i + =0.1)6printf"%lf\n", i);7     return 0;8}

Will this program stop at 10??? The answer is no.

Causes of the above traps

In fact, all data in the computer is represented by a binary representation, including floating-point numbers. This causes some floating-point numbers not to be represented in binary precision, such as 0.1 (which is easy to understand, as 10/3 cannot be represented by a decimal)

Further, floating-point numbers are represented by a fraction + exponent, for example

0.5 = 1/2

0.75 = 1/2 + 1/(2^2)

0.875 = 1/2 + 1/(2^2) + 1/(2^3)

0.1 = 1/(2^4) + 1/(2^5) + 1/(2^8) + ...

0.1 of them can loop indefinitely, which means that 0.1 cannot be accurately represented in a computer, so creating these traps is easy to understand.

Traps for floating-point numbers

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.