The code below gives different result depending on environments:
fn main() {
let n: usize = 5489031744;
let n_cbrt: usize = (n as f64).cbrt().floor() as usize;
println!("{}", n_cbrt);
}
Rust Playground and my Linux server (Ryzen) gives
1763
though M1 Macbook Air gives
1764
Mathematically, 1764.pow(3)
exactly equals 5489031744
so the latter result is correct. But, anyway, the problem is the inconsistency rather than mathematical correctness.
Is this inconsistency a bug? If not, does this mean we cannot write a cross-platform application whose behavior is fully predictable and consistent in Rust?
By the way, the C++ program below gives 1764
in both my Linux server (Ryzen) and M1 Macbook Air (and in an online compiler).
#include <iostream>
#include <cmath>
int main() {
std::cout << cbrt(5489031744) << "\n";
}
Very strange as it seems Rust's cbrt()
calls C++'s cbrt()
directly (source):
pub fn cbrt(self) -> f64 {
unsafe { cmath::cbrt(self) }
}
Summary:
Environment | Rust | C++ |
---|---|---|
Linux (Ryzen) | 1763 | 1764 (clang++ , g++ ) |
macOS (M1) | 1764 | 1764 (clang++ , g++ ) |
Rust Playground | 1763 | |
C++ online compiler | 1764 (g++ ) |
|
FreeBSD (Intel) | 1764 | 1764 (clang++ , g++ ) |