Precautions for comparing double data

Source: Internet
Author: User
Precautions for comparing double data

Console. writeline (7.88 + 5.00 = 12.88 );

Result:FalseWhy?

Analysis:

We use "=" to compare the two double types that should be equal, and return the true value is completely uncertain. The principle of the computer's calculation of floating point numbers is to ensure that the necessary precision is correct, for example, double A = 0.9 + 0.2; then it can only ensure that the precision of the first digit after the decimal point is correct, the result of the addition calculated by the computer may be 1.100000001, or 1.100000002 or 1.1. That is to say, after the computer calculation, it is not guaranteed that all of the values below 0.1 are correct, therefore, it is not feasible to directly use = for comparison.
We know that data is stored as 1 or 0 on a computer.

Solution:

To compare the two double numbers, check whether the absolute value of the subtraction is smaller than a certain value. This value is generally lower than the accuracy of the two numbers.

Example: console. writeline (math. Abs (7.88 + 5.00-12.88) <0.001 );

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.