Rust 是否定义了将非有限浮点数转换为整数时会发生什么?

Does Rust define what happens when you cast a non-finite float to an integer?

我认为传统上,所有退化浮点数都被称为“NaN”,但 Rust 似乎区分三种退化浮点数:+inf、-inf 和 nan(这就是为什么我使用术语“非-finite”而不是“nan”或“infinite”)。

当您尝试将它们转换为整数(例如 u64)时会发生什么?有定义的行为吗?如果是这样,定义的行为是什么?

我认为这是未定义的。 reddit 上一个 7 年前的帖子说它是未定义的,但从那以后事情可能已经改变了。

在“Rust by Example”中,似乎是说 nan 被转换为 0。

根据我的实验,它在实践中不会恐慌,所以除非编译器中存在明显的错误,否则我假设该行为未定义为“恐慌”。

这在 Rust 参考 here 中定义为:

Numeric cast

Casting from a float to an integer will round the float towards zero

  • NaN will return 0

  • Values larger than the maximum integer value, including INFINITY, will saturate to the maximum value of the integer type.

  • Values smaller than the minimum integer value, including NEG_INFINITY, will saturate to the minimum value of the integer type.