Lyricdev
GitHub

LYR-SEM0205

an equality test on floats

warning · spec 08-expressions · lint float-equality, group correctness, allow unless said

== or != with a float or float32 on both sides. Not said unless the lint is set to warn.

Explanation

Floating-point arithmetic rounds, so two computations of the same value can differ in the last bit: 0.1 + 0.2 == 0.3 is false. An exact test is right for values that were never computed, and wrong for most others.

Compare the difference with a tolerance. The lint is allow by default; -W float-equality or [lints] warn = ["float-equality"] turns it on.

Wrong

@Warn("float-equality")
fn main(): void {
    let a = 0.1 + 0.2;
    let _ = a == 0.3;
}
@Warn("float-equality")
fn main(): void {
    let a = 0.1 + 0.2;
    let d = a - 0.3;
    let _ = d < 0.000001 && d > -0.000001;
}