Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check whether a vector is equal to another vector that contains NaN and inf?

Tags:

rust

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?

like image 285
The Unfun Cat Avatar asked Nov 23 '16 15:11

The Unfun Cat


People also ask

Is NaN () in R?

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.

How do I find NaN values in R?

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.

What does INF mean R?

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.

Is NaN in Dataframe R?

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.


2 Answers

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

like image 160
Chris Emerson Avatar answered Oct 20 '22 11:10

Chris Emerson


You might be interested in the is_nan method.

assert!(nan.is_nan());
like image 41
Matthieu M. Avatar answered Oct 20 '22 11:10

Matthieu M.