Rust中f64的cbrt跨环境结果不一致问题问询
跨平台下Rust与C++立方根计算结果不一致问题
以下Rust代码在不同环境运行结果存在差异:
fn main() { let n: usize = 5489031744; let n_cbrt: usize = (n as f64).cbrt().floor() as usize; println!("{}", n_cbrt); }
- Rust Playground、Linux(Ryzen)服务器输出:
1763 - M1 MacBook Air输出:
1764
从数学上看,1764.pow(3)精确等于5489031744,后者结果正确,但核心问题是跨平台结果不一致。
疑问
这种不一致属于bug吗?若不是,是否意味着无法编写行为完全可预测且一致的跨平台Rust应用?
C++对比情况
以下C++程序在Linux(Ryzen)、M1 MacBook Air及在线编译器中均输出1764:
#include <iostream> #include <cmath> int main() { std::cout << cbrt(5489031744) << "\n"; }
值得注意的是,Rust的f64::cbrt函数直接调用了C标准库的cbrt实现:
pub fn cbrt(self) -> f64 { unsafe { cmath::cbrt(self) } }
结果汇总
| 环境 | Rust | C++ |
|---|---|---|
| Linux(Ryzen) | 1763 | 1764(clang++、g++) |
| macOS(M1) | 1764 | 1764(clang++、g++) |
| Rust Playground | 1763 | - |
| C++在线编译器 | - | 1764(g++) |
| FreeBSD(Intel) | 1764 | 1764(clang++、g++) |
内容的提问来源于stack exchange,提问作者ynn
相关产品推荐
相关产品推荐

