Reputation: 22603
I believe that traditionally, all degenerate floats are referred to as "NaN", but Rust seems to distinguish between three kinds of degenerate floats: +inf, -inf, and nan (that's why I use the term "non-finite" in the title instead of "nan" or "infinite").
What happens when you try to cast these to an integer, such as u64? Is there a defined behavior? If so, what is the defined behavior?
I would assume that this is undefined. A 7 year old thread on reddit says it's undefined, but things might have changed since then.
In "Rust by Example", it seems to say that nan gets converted to 0.
Based on my experiments, it does not panic in practice, so unless there is a blatant bug in the compiler, I assume the behavior is not defined as "panics".
Upvotes: 4
Views: 455
Reputation: 222108
This is defined in the Rust Reference here as:
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.
Upvotes: 8