我想判断一个整数是否是2的幂.我的标准方法是看log₂(x)是否是一个整数值,但我没有找到优雅的方法来做到这一点.我的方法如下:

let x = 65;

let y = (x as f64).log(2.0);

// Compute the difference between y and the result of
// of truncating y by casting to int and back
let difference = y - (y as i64 as f64);

// This looks nice but matches on float values will be phased out
match difference {
    0.0 => println!("{} is a power of 2", x),
    _ => println!("{} is NO power of 2", x),
}

// This seems kind of clunky
if difference == 0.0 {
    println!("{} is a power of 2", x);
} else {
    println!("{} is NO power of 2", x);
}

Is there a builtin option in Rust to check if a float can be converted to an integer without truncation?

行为类似于:

42.0f64.is_int() // True/ Ok()
42.23f64.is_int() // False/ Err()

换句话说,一个方法/宏/等,它允许我判断通过强制转换为int是否会丢失信息(小数).


I already found that checking whether an integer is a power of 2 can be done efficiently with 100.

推荐答案

可以使用fract判断是否存在非零分数部分:

42.0f64.fract() == 0.0;
42.23f64.fract() != 0.0;

请注意,只有当您已经知道数字在范围内时,这才有效.如果需要额外的判断来测试浮点数是否在0和u32::MAX之间(或i32::MINi32::MAX之间),那么最好进行转换并判断它是否丢失精度:

x == (x as u32) as f64

Rust相关问答推荐

使用windows crate Rust 展示windows

获取字符串切片(&;str)上的切片([ia..ib])返回字符串

自定义结果枚举如何支持`?`/`FromResidual`?

在rust sqlx中使用ilike和push bind

在生存期内将非静态可变引用转换为范围内的静态可变引用

更合理的方法来设计样条线函数器?

在macro_rule中拆分模块和函数名

为什么`str`类型可以是任意大小(未知大小),而`string`类型的大小应该是已知的?

在为第三方 struct 实现第三方特征时避免包装器的任何方法

为什么 Rust 创建的 f32 小于 f32::MIN_POSITIVE?

在没有任何同步的情况下以非原子方式更新由宽松原子操作 Select 的值是否安全?

Rust中如何实现一个与Sized相反的负特性(Unsized)

是否可以通过可变引用推进可变切片?

切片不能被 `usize` 索引?

如何在 use_effect_with_deps 中设置监听器内的状态?

将 `&T` 转换为新类型 `&N`

只有一个字符被读入作为词法分析器的输入

TcpStream::connect - 匹配武器具有不兼容的类型

类型组的通用枚举

为什么 u64::trailing_zeros() 在无分支工作时生成分支程序集?