rust-num / num-traits

Numeric traits for generic mathematics in Rust
Apache License 2.0
719 stars 133 forks source link

Clarify example for trait method `float::Float::integer_decode` #326

Closed mtilda closed 3 months ago

mtilda commented 3 months ago

Fixes https://github.com/rust-lang/rust/issues/126610

Problem

The example for trait method float::Float::integer_decode fails if num is changed to most any value other than 2.

use num_traits::Float;

let num = 2.0f32;

// (8388608, -22, 1)
let (mantissa, exponent, sign) = Float::integer_decode(num);
let sign_f = sign as f32;
let mantissa_f = mantissa as f32;
let exponent_f = num.powf(exponent as f32);

// 1 * 8388608 * 2^(-22) == 2
let abs_difference = (sign_f * mantissa_f * exponent_f - num).abs();

assert!(abs_difference < 1e-10);

Changes

Updated example

use num_traits::Float;

let num = 42_f32;

// (11010048, -18, 1)
let (mantissa, exponent, sign) = Float::integer_decode(num);
let sign_f = sign as f32;
let mantissa_f = mantissa as f32;
let exponent_f = exponent as f32;

// 1 * 11010048 * 2^(-18) == 42
let abs_difference = (sign_f * mantissa_f * exponent_f.exp2() - num).abs();

assert!(abs_difference < 1e-10);