rhaiscript / rhai

Rhai - An embedded scripting language for Rust.
https://crates.io/crates/rhai
Apache License 2.0
3.79k stars 177 forks source link

NaN handling for f32/f64 sign implementation #446

Closed Kaiser1989 closed 2 years ago

Kaiser1989 commented 3 years ago

Function sign for f32 or f64 return 1 for NaN values.

print(sign(1.0 / 0.0));

Waiting for Web Worker to finish loading... Running script at 2021-09-14T13:10:34.758Z

[PRINT] 1

Script returned: "" Finished at 2021-09-14T13:10:34.763Z

https://github.com/rhaiscript/rhai/blob/master/src/packages/arithmetic.rs (line 332 and 440)

So instead of using:

pub fn sign(x: f32) -> INT {
    if x == 0.0 {
        0
    } else if x < 0.0 {
        -1
    } else {
        1
    }
}

it's best to use Rust's signum handling:

pub fn sign(x: f32) -> INT {
    x.signum() as INT  // signum of NaN => NaN, Nan as INT => 0
}
schungx commented 3 years ago

I'll actually test for zero first as the sign function in Rhai maps zero to zero sign.

This will go into the next released version.

schungx commented 2 years ago

Closing this as the new sign implementation is now live.