The following code produces the result -inf
.
fn main() {
println!("{}", (-10. / 0.));
}
However, when I tried the following code, it didn't print true
, instead it gave me an error.
fn main() {
println!("{}", (-10. / 0.) == -inf);
}
What value should I give instead of -inf
to get true
printed out?
what is
-inf
?
It's negative infinity as defined in the IEEE floating point standard. It's the result of dividing negative floating point numbers by zero.
However, when I tried the following code, it didn't print true, instead it gave me an error.
fn main() { println!("{}", (-10. / 0.) == -inf); }
Rust does not define a global variable or keyword named inf
. So you can't use inf
unless you first define (or import from somewhere) a variable with that name. -inf
is just the string you get when converting negative infinity to a string. It's not a valid floating point literal by itself.
What value should I give instead of -inf to get true printed out?
You could use the constants INFINITY
or NEG_INFINITY
from the given floating point type, such as -10. / 0. == std::f64::NEG_INFINITY
or -10. / 0. == -std::f64::INFINITY
. Or you could define let inf = 1. / 0.;
, then (-10. / 0.) == -inf
would be true. Or you could just directly write -10. / 0. == -1. / 0.
or any other expression that results in negative infinity.
What type is
-inf
?
The type of -inf
is the same as that of the floating point numbers that you divided to get -inf
. If you divide two f32
s, you'll get an f32
, and if you divide two f64
s, you'll get an f64
. If the type of the operands hasn't been decided yet, the type of the result will be {float}
until a more concrete type has been decided.
Note that this isn't any different than any other case of dividing two floating point numbers (or adding them, multiplying them etc.). In other words, x / y
where y
is 0. has the exact same type as x / y
where y
is any other floating point number.
As stated by sepp2k, -inf
is not valid Rust syntax. To check for infinite values, try f64::is_finite()
or comparing to constants std::f64::INFINITY
and std::f64::NEG_INFINITY
.
fn main() {
let result: f64 = -10. / 0.;
println!("{}", result.is_infinite()); // true
println!("{}", result == std::f64::INFINITY); // false
println!("{}", result == std::f64::NEG_INFINITY); // true
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With