I have a test of division, where I sometimes need to check that my results are either NaN or inf, but it seems like Rust does not consider NaN to be equal to NaN:
fn main() {
let nan = "NaN".parse::<f64>().unwrap();
println!("{:?}", nan);
println!("{:?}", nan == nan);
} // NaN false
How do I compare two vectors that contain NaN and infinity to see whether they are equal?
nan() Function. is. nan() Function in R Language is used to check if the vector contains any NaN(Not a Number) value as element. It returns a boolean value for all the elements of the vector.
To check NaN values in R, use the is. nan() function. The is. nan() is a built-in R function that tests the object's value and returns TRUE if it finds the NaN value; otherwise, it returns FALSE.
Inf and -Inf stands for infinity (or negative infinity) and is a result of storing either a large number or a product that is a result of division by zero. Inf is a reserved word and is – in most cases – product of computations in R language and therefore very rarely a product of data import.
The NaN values are referred to as the Not A Number in R. It is also called undefined or unrepresentable but it belongs to numeric data type for the values that are not numeric, especially in case of floating-point arithmetic. To remove rows from data frame in R that contains NaN, we can use the function na. omit.
NaNs by definition compare unequal. If you want to do something different you've got to define the comparison by yourself. It's not too difficult; the iterator methods do most of the work for you:
fn eq_with_nan_eq(a: f64, b: f64) -> bool {
(a.is_nan() && b.is_nan()) || (a == b)
}
fn vec_compare(va: &[f64], vb: &[f64]) -> bool {
(va.len() == vb.len()) && // zip stops at the shortest
va.iter()
.zip(vb)
.all(|(a,b)| eq_with_nan_eq(*a,*b))
}
fn main() {
use std::f64::NAN;
let a = vec![0f64, 1.0, NAN];
let b = vec![0f64, 2.0, NAN];
let c = vec![0f64, 1.0, NAN, 4.0];
let d = vec![0f64, 1.0, 3.0];
assert_eq!(vec_compare(&a, &b), false);
assert_eq!(vec_compare(&a, &a), true);
assert_eq!(vec_compare(&a, &d), false);
assert_eq!(vec_compare(&a, &c), false);
}
Playground
You might be interested in the is_nan method.
assert!(nan.is_nan());
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