Home >Backend Development >C++ >Why Does Floating-Point Arithmetic in C Lead to Precision Issues?

Why Does Floating-Point Arithmetic in C Lead to Precision Issues?

DDD
DDDOriginal
2024-11-04 11:20:02942browse

Why Does Floating-Point Arithmetic in C   Lead to Precision Issues?

Floating-Point Precision Quirks in C

Floating-point arithmetic in C exhibits behaviors that can be counterintuitive. Consider the following:

The expression double a = 0.3; assigns a value that logically represents 0.3 to the variable a. However, the output of std::cout << a << std::endl; with 20 decimal places of precision shows "0.2999999999999999889." This deviation suggests that the internal storage of the floating-point number differs from its logical value.

Similarly, in the loop where a is repeatedly added to b, the result at the end of the loop (50 iterations) is "15.000000000000014211," which is higher than it should be. This outcome demonstrates how rounding errors can accumulate over multiple operations.

To circumvent these precision issues, it is important to avoid setting the precision of floating-point values higher than the actual precision of the data type. This can be achieved using the following approach:

#include 
#include 

int main() {
    double a = 0.3;
    std::cout.precision(std::numeric_limits::digits10);
    std::cout << a << std::endl;

    double b = 0;
    for (char i = 1; i <= 50; i++) {
        b = b + a;
    }

    std::cout.precision(std::numeric_limits::digits10);
    std::cout << b << std::endl;
}

By setting the precision to the maximum available precision of the double data type, the output will accurately represent the stored values. However, if the loop is run for a significantly larger number of iterations (e.g., 5000 instead of 50), the accumulated error will still become noticeable due to inherent limitations of floating-point arithmetic.

The above is the detailed content of Why Does Floating-Point Arithmetic in C Lead to Precision Issues?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn