Home > Backend Development > C++ > body text

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

Mary-Kate Olsen
Release: 2024-11-04 13:06:02
Original
349 people have browsed it

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

Floating-Point Precision in C

In C , floating-point numbers are precise up to a certain number of decimal places. However, there are limitations to this precision, which can lead to unexpected results.

Problem Statement

Consider the following code snippet:

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

// Print 0.2999999999999999889

double a, b;
a = 0.3;
b = 0;
for (char i = 1; i <= 50; i++) {
  b = b + a;
};
std::cout.precision(20);
std::cout << b << std::endl;

// Print 15.000000000000014211
Copy after login

As illustrated, a is slightly less than 0.3, but when multiplied by 50, b becomes slightly greater than 15.0. This deviation from the expected result can be attributed to the limitations of floating-point precision.

Solution

To obtain the correct results, it is crucial to avoid setting the precision higher than the available precision for the numeric type. The following revised code snippet demonstrates this approach:

<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 approach ensures that the precision is set to the maximum available for the double data type. It is important to note that if the loop were to run for a significantly larger number of iterations, such as 5000 instead of 50, the accumulated error would eventually become noticeable, regardless of the precision setting. This is an inherent limitation of floating-point arithmetic.

The above is the detailed content of Why Does Floating-Point Arithmetic in C Lead to Precision Errors?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!