Skip to content

Guarantees (or lack thereof) of floating-point arithmetic #123

Closed
@gnzlbg

Description

@gnzlbg

Once we are finished with layout and validity we might want to write down what unsafe Rust code is allowed to assume about floating-point arithmetic with the f32 and f64 primitive types.

For example, does this code (playground) invoke undefined behavior?

fn foo(num: f32) -> f32 {
    ((num + 0.1) / 1.5e38) * 1.5e38
}

const A: f32 = 0.00000014156103134155273437500000000000000000000000;

fn main() {
    let expr =  foo(1.23456789) - 1.23456789 - 0.1;
    let idx = if expr == A {
        0
    } else {
        1
    };
    let a = [0];
    // With IEEE-754 arithmetic this is always safe:
    let r = unsafe { a.get_unchecked(idx) };
    println!("r = {}", r);
}

Currently, this code does not invoke UB on many targets, but on i586-unknown-linux-gnu in debug mode this code does an access out-of-bounds.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-floatsTopic: concerns floating point operations/representationsC-open-questionCategory: An open question that we should revisitS-pending-designStatus: Resolving this issue requires addressing some open design questions

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions