JavaScript is not currently enabled, but is required for full CodeSonar manual search and browse functionality.

If you are viewing this file in your hub's Web GUI, enable JavaScript in your browser: you will also need it for GUI functionality.

If you opened this file directly from disk, your browser may be directly suppressing JavaScript functionality: certain browsers perform this suppression on local files (but not files delivered by web servers) for security reasons.

CodeSonar® 9.2p0 CONFIDENTIAL CodeSecure Inc
Java


JAVA.ARITH.FPEQUAL : Floating Point Equality (Java)

Summary

A comparison between non-integral values might be unreliable.

Floating point operations are by nature approximated. This can introduce bugs when precise, mathematical properties are expected from inherently imprecise floating point computations. Moreover, computations that might lose precision or overflow, whose result is stored in a larger type, are suspicious since, by computing on the larger type from the beginning, one could avoid approximations and overflows.

Properties

Class Name Floating Point Equality (Java)
Significance reliability
Mnemonic JAVA.ARITH.FPEQUAL
Categories
CWE CWE:1077 Floating Point Comparison with Incorrect Operator
CERT-Java CERT-Java:NUM12-J Ensure conversions of numeric types to narrower types do not result in lost or misinterpreted data
Availability Available for Java and Kotlin.
Enabling Checks for this warning class are enabled by default. To disable them, add the following WARNING_FILTER rule to the project configuration file.
WARNING_FILTER += discard class="Floating Point Equality (Java)"

Example

public class Approximation {

  public static void main(String[] args) {
    for (double d = 0.0; d != 5.0; d += 0.001) // "Floating Point Equality (Java)" warning issued here

      System.out.println(d);
  }
}

The comparison between d != 5.0 will always yield true, because of approximations in the computation d += 0.001. The while loop will thus never terminate.

In this example, the programmer should replace d != 5.0 with d < 5.0 or replace floating point computations with (stable and more efficient) integral computations.

for (int d = 0; d != 5000; d++)
  System.out.println(d / 1000.0);

Resolution

Use approximated comparisons (up to some epsilon) rather than exact comparisons. Use integral numbers instead of floating point values, whenever possible. Compute over integral numbers and translate into floating points only at the end, whenever possible. If a large type for the result of a computation is desired, compute from the beginning on that type instead of applying a type conversion at the end of the computation.

Relevant Configuration File Parameters

The following configuration file parameters affect checks for this warning class.

 

To report problems with this documentation, please visit https://support.codesecure.com/.