Skip to content

<f64 as FromStr> produces incorrect results in some cases #23505

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
JRoush opened this issue Mar 19, 2015 · 3 comments
Closed

<f64 as FromStr> produces incorrect results in some cases #23505

JRoush opened this issue Mar 19, 2015 · 3 comments

Comments

@JRoush
Copy link

JRoush commented Mar 19, 2015

In at least one case (and presumably more), FromStr::from_str() produces a result that is off by one ulp.

Example:

pub fn main() {
    use std::str::FromStr;    
    let literal: f64 = 0.123f64;
    let fromstr: f64 = FromStr::from_str("0.123").unwrap();
    println!("Literal: {:16X}", as_int(literal)); // Literal: 3FBF7CED916872B0
    println!("FromStr: {:16X}", as_int(fromstr)); // FromStr: 3FBF7CED916872B1
    println!("Equal: {}", literal == fromstr);    // Equal: false
}

pub fn as_int(f: f64) -> u64 {
    unsafe{ std::mem::transmute::<f64,u64>(f) }
}

Here the compiler produces the correct result for the literal value but the runtime parsing function produces a different, incorrect result. The difference is tiny, but of course it is enough to cause problems :)

For the record, here is the output of rustc --version --verbose on my system:

rustc 1.0.0-nightly (30e1f9a1c 2015-03-14) (built 2015-03-15)
binary: rustc
commit-hash: 30e1f9a1c2bf7134135800bc9afd082773defadc
commit-date: 2015-03-14
build-date: 2015-03-15
host: x86_64-unknown-linux-gnu
release: 1.0.0-nightly
@lifthrasiir
Copy link
Contributor

I assume this is a duplicate of #7648. We have really hairy decimal to floating point routine right now.

@JRoush
Copy link
Author

JRoush commented Mar 19, 2015

@lifthrasiir Whoops, looks like you are right.

@steveklabnik
Copy link
Member

closing as duplicate

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants