We've time-stream of regularly taken data, but at some points no data is taken so we place a QNAN in the array at that point. Only problem is, whenever we do any statistics on the data, every time we access a location we have to check that it isn't a NAN. So our routines for the mean look like
int n = 0;
double sum = 0;
for(int i = 0; i < SIZE; i++)
{
if(data[i] == data[i])
{
sum += data[i];
n++;
}
}
We're probably always going to have to count the NAN's, but would be nice if there was a way of saying, if you add an invalid value to a valid number, the valid number remains the same.
I'm not sure there's a better way of doing this, but wanted to check. Thanks, James
You cannot do what you ask with NAN since arithmetic on NANs does not do what you need. The result of an addition containing a NAN operand is a NAN.
You are looking for an additive identity. Which means you'd need to put zero in the array. Now, if you do that then you'll have to keep track elsewhere of which elements are invalid and deal with that accordingly. But if you want to be able to sum an array of values, and have certain values make no contribution, your only option is for those values to be zero.
Frankly I think your current solution is as good as you'll get, modulo the use of std::isnan() to check for 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