Skip to content

Floating point modulo producing incorrect compuations #111405

Open
@Gip-Gip

Description

@Gip-Gip

I tried this code:

fn ieee_mod(a: f32, b: f32) -> f32 {
  a - (a / b).round() * b
}

fn libc_mod(a: f32, b: f32) -> f32 {
  a % b
}


fn main() {
    let x = 1.5 * 3.14;
    let y = 0.5 * 3.14;
    
    assert_eq!(ieee_mod(x, y), libc_mod(x, y));
}

I expected the assert to pass.

Instead, this happened:

thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `0.0`,
 right: `1.5699999`', bug.rs:14:5

Meta

This is most likely due to division being rounded, but mod not. This caused a bug in a sin table function I was writing.

This is standard libc behavior but it is still not correct and can cause bugs where none are expected.

rustc --version --verbose:

rustc 1.69.0 (84c898d65 2023-04-16)
binary: rustc
commit-hash: 84c898d65adf2f39a5a98507f1fe0ce10a2b8dbc
commit-date: 2023-04-16
host: x86_64-unknown-linux-gnu
release: 1.69.0
LLVM version: 15.0.7
Backtrace

stack backtrace:
   0: rust_begin_unwind
             at /rustc/84c898d65adf2f39a5a98507f1fe0ce10a2b8dbc/library/std/src/panicking.rs:579:5
   1: core::panicking::panic_fmt
             at /rustc/84c898d65adf2f39a5a98507f1fe0ce10a2b8dbc/library/core/src/panicking.rs:64:14
   2: core::panicking::assert_failed_inner
   3: core::panicking::assert_failed
   4: bug::main
   5: core::ops::function::FnOnce::call_once
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-floating-pointArea: Floating point numbers and arithmeticC-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions