Home > Net >  C add values of a vector that might contain NaN values
C add values of a vector that might contain NaN values

Time:11-30

I am a C noob.

What I am trying to do is sum the values of a vector of doubles (let's call it x) and ignore any values that are NaN. I tried to look this up, but I couldn't find anything specifically referencing what would happen if a vector contains any NaN values.

E.g.:

// let's say x = [1.0, 2.0, 3.0, nan, 4.0]
y = sum(x) // y should be equal to 10.0

Would the accumulate function work here? Or would it return NaN if x contains a NaN? Would a for loop work here with a condition to check for if the value is NaN (if yes, how do I check if NaN? In Python, the language I know best, this kind of check is not always straightforward).

CodePudding user response:

std::isnan returns true if the passed floating point value is not a number. You have to add this check to all functions to avoid including NANs in your calculations. For example for sum:

constexpr auto sum(auto list) {
    typename decltype(list)::value_type result = 0;

    for (const auto& i : list) {
        if (!std::isnan(i)) { // < - crucial check here
            result  = i;
        }
    }
    return result;
}

Demo:

int main() {
    auto list = std::array{ 1.0f, 2.0f, 3.0f, NAN };
    std::cout << sum(list); //prints out 6
}

CodePudding user response:

you could use std::accumulate with a custom summation operation.

const std::vector<double> myVector{1.0, 2.0, 3.0, std::nan("42"), 4.0};

auto nansum = [](const double a, const double b)
{
  return a   (std::isnan(b) ? 0 : b);
}

auto mySum = std::accumulate(myVector.begin(), myVector.end(), 0, nansum);
  • Related