Skip to content

Warn against exact floating-point comparsions. #8583

@zvavybir

Description

@zvavybir

What it does

Warns against usage of exact comparison operators (== and !=, not things like > or <=) since floating point numbers rarely are exactly equal.

Where I got the idea from: https://gforth.org/manual/Floating-Point-Tutorial.html
Prior art: https://users.rust-lang.org/t/comparing-floats-for-equality/54523 and https://bitbashing.io/comparing-floats.html

Lint Name

exact-floating-point

Category

pedantic

Advantage

  • Avoids subtle errors

Drawbacks

There might be occasions where the programmer knows that the value is exact (e.g. inf or nan should be common – although they should be handled by dedicated functions).

Example

let a = 0.1f64;
let b = 0.2f64;
if a + b == 0.3
{
  println!("This isn't reachable!");
}

Could be written as:

let a = 0.1f64;
let b = 0.2;
if (a + b - 0.3).abs() < 0.001*((a+b).abs()+0.3f64.abs())
{
  println!("This is reachable!");
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions