[英]Where is the frexp function for f32 in Rust?
我在以前的版本中发现了一些有关std :: f32不稳定功能的引用
如果您单击链接,您会看到该功能不稳定(如您所说),并且相应的问题(#27752)已关闭。 因此,该功能部件不再可用(在PR#41437中删除)。
我还找到了对
std::num::Float
引用
如果您查看该URL,您会注意到,这是2015年的文档,因此也已弃用。
不幸的是,我找不到任何可以为您提供Rust实现的板条箱,但是由于Rust具有完整的FFI支持,因此您可以调用相应的c函数。
use std::os::raw::{c_float, c_double, c_int};
extern "C" {
fn frexp(x: c_double, exp: *mut c_int) -> c_double;
fn frexpf(x: c_float, exp: *mut c_int) -> c_float;
}
pub trait FloatExp: Sized {
fn frexp(self) -> (Self, i32);
}
impl FloatExp for f64 {
fn frexp(self) -> (Self, i32) {
let mut exp: c_int = 0;
let res = unsafe { frexp(self, &mut exp) };
(res, exp)
}
}
impl FloatExp for f32 {
fn frexp(self) -> (Self, i32) {
let mut exp: c_int = 0;
let res = unsafe { frexpf(self, &mut exp) };
(res, exp)
}
}
fn main() {
println!("{:?}", (1.3f64).frexp());
println!("{:?}", (0.3f32).frexp());
}
( 游乐场 )
此功能已被弃用很长时间了。 这是完全删除它的提交: https : //github.com/rust-lang/rust/pull/41437 。
您可能有一个新版本。 如果您有兴趣,可以在这里找到完整的实现https://github.com/rust-lang/rust/blob/9ebf47851a357faa4cd97f4b1dc7835f6376e639/src/librustc_apfloat/tests/ieee.rs ,但是您可能应该改用其他方法。
例如,检出Float
特性Float
_ integer_decode
,它返回尾数,指数和符号。
直接来自我链接到的文档:
use num_traits::Float;
let num = 2.0f32;
// (8388608, -22, 1)
let (mantissa, exponent, sign) = Float::integer_decode(num);
我在glm-rs lib中找到了frexp()
的Rust实现。
fn frexp(self) -> ($t, isize) {
// CHECK: use impl in `libstd` after it's stable.
if self.is_zero() || self.is_infinite() || self.is_nan() {
(self, 0)
} else {
let lg = self.abs().log2();
let x = (lg.fract() - 1.).exp2();
let exp = lg.floor() + 1.;
(self.signum() * x, exp as isize)
}
}
有趣的是,它没有给我与C frexpf()
相同的结果,因为f32.fract()
对于负输入返回负数。 我通过用lg - lg.floor()
替换lg.fract()
解决了它。
我的版本:
fn frexp(s : f32) -> (f32, i32) {
if 0.0 == s {
return (s, 0);
} else {
let lg = s.abs().log2();
let x = (lg - lg.floor() - 1.0).exp2();
let exp = lg.floor() + 1.0;
(s.signum() * x, exp as i32)
}
}
例:
let x = 0.3f32;
println!("{:?}", (x).frexp()); // (0.6, -1)
println!("{:?}", glmfrexp(x)); // (0.3, -1)
println!("{:?}", myfrexp(x)); // (0.6, -1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.