Home > Backend Development > C++ > How to Ensure Accurate Floating-Point Precision in C ?

How to Ensure Accurate Floating-Point Precision in C ?

Barbara Streisand
Release: 2024-11-05 16:32:02
Original
474 people have browsed it

How to Ensure Accurate Floating-Point Precision in C  ?

Floating-Point Precision in C

When dealing with floating-point numbers in C , it is essential to understand their precision limitations. Consider the following code:

<code class="cpp">double a = 0.3;
std::cout.precision(20);
std::cout << a << std::endl;
Copy after login

The result is 0.2999999999999999889 instead of 0.3, indicating a loss of precision. To address this, C provides the std::numeric_limits::digits10 constant, where T is the type of the floating-point number. This constant represents the maximum number of significant digits that can be represented accurately.

Here's how to use std::numeric_limits::digits10 to set the precision correctly:

<code class="cpp">#include <iostream>
#include <limits>
int main()
{
        double a = 0.3;
        std::cout.precision(std::numeric_limits<double>::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<double>::digits10);
        std::cout << b << std::endl;
}</code>
Copy after login

This code sets the precision to the maximum number of significant digits that can be represented accurately by a double. As a result, the output will be 0.3 in both cases.

However, it is important to note that even with this approach, accumulated errors may occur if the loop iterates significantly more than 50 times. This is because floating-point numbers are an approximation, and errors can accumulate over a series of operations. To handle such situations, it is recommended to use libraries that provide arbitrary-precision arithmetic, such as Boost.Multiprecision.

The above is the detailed content of How to Ensure Accurate Floating-Point Precision in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template