Home >Backend Development >C++ >How Can Floating-Point Values Be Compared Accurately While Accounting for Precision Loss?

How Can Floating-Point Values Be Compared Accurately While Accounting for Precision Loss?

Susan Sarandon
Susan SarandonOriginal
2024-12-25 07:48:33864browse

How Can Floating-Point Values Be Compared Accurately While Accounting for Precision Loss?

Comparing Floating-Point Values with Precision Conservation

Floating-point comparison poses a challenge due to precision loss. Simply comparing doubles or floats using == is unreliable.

Epsilon-based Comparison

One approach involves using an epsilon (ε) threshold to account for precision loss:

bool CompareDoubles2(double A, double B) {
  double diff = A - B;
  return (diff < EPSILON) && (-diff < EPSILON);
}

However, this approach can be inefficient.

Context-Dependent Considerations

The choice of comparison method depends on the context and expected values. Consider the following potential pitfalls:

  • Presuming a == b and b == c implies a == c.
  • Using the same epsilon for different units of measurement.
  • Using epsilon for both angles and line lengths.
  • Sorting using such a comparison function.

Standard Epsilon

std::numeric_limits::epsilon() represents the difference between 1.0 and the next value representable by a double. It can be used in comparison functions, but only if expected values are less than 1.

Consequences of Integer Arithmetic

Using doubles to hold integer values can lead to correct arithmetic, as long as fractions or values outside the range of an integer are avoided. For example, 4.0/2.0 will equal 1.0 1.0.

The above is the detailed content of How Can Floating-Point Values Be Compared Accurately While Accounting for Precision Loss?. 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