Floating point Trap

Source: Internet
Author: User

Trap One

if (0.1+0.1+0.10.3)      printf ("equal\n" );   Else       printf ("notequal\n");  

Does it output "equal"? No! Actual floating-point arithmetic,0.1+0.1+0.1! = 0.3

Trap Two

Double i;  for (i=0; i!=; i+=0.1)    printf ("%.1lf\n", i);

Will the program end the loop from 0.0 to 9.9? No! Because I can never be equal to ten, this will be infinite loop

Causes of the above traps

All data in the computer is represented in binary notation, including floating-point numbers, which causes some floating-point numbers not to be represented by binary precision, such as 0.1(which is easy to understand, like 10/3=0.33333 ...). cannot be represented exactly as a decimal)

For example:

(0.5) 10 = 2-1 = (0.1) 2

(0.75) 10 = 2-1 + 2-2 = (0.11) 2

(0.875) 10 = 2-1 + 2-2 + 2-3 = (0.111) 2

(0.1) 10 = 2-4 + 2-5 + 2-8 + ... = (0.00011001 ...) 2

0.1 of them can loop indefinitely, which means that 0.1 cannot be accurately represented in the computer, so it is easy to understand that these two traps are involved in a 0.1 participation operation that cannot be represented by a binary precision, so the expected results are not obtained. For example, trap two, change the step size to a binary precise representation of 0.5, will not be infinite loop down.

Floating point Trap

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.