Home >Backend Development >C++ >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;
The result is 0.2999999999999999889 instead of 0.3, indicating a loss of precision. To address this, C provides the std::numeric_limits Here's how to use std::numeric_limits 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!<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>