lets say you have a std::complex<double> array[N];
how would you set all -inf
and inf
values to 0 in a for loop?
std::isinf
won't work for me the compiler predates C++11
lets say you have a std::complex<double> array[N];
how would you set all -inf
and inf
values to 0 in a for loop?
std::isinf
won't work for me the compiler predates C++11
Try this: std::numeric_limits<double>::infinity()
will provide a value that tells you whether a number is an infinity or not.
Here is an example code for a vector
of double
values; you can change the repl_inf
to use complex<double>
instead.
#include <iostream>
#include <algorithm>
#include <vector>
#include <limits>
using namespace std;
int repl_inf (double v) { return (v== std::numeric_limits<double>::infinity() || -v== std::numeric_limits<double>::infinity()) ? 0.0 : v; }
int main() {
vector<double> v;
v.push_back(1);
v.push_back(1.0/0.0);
v.push_back(2);
v.push_back(-1.0/0.0);
transform (v.begin(), v.end(), v.begin(), repl_inf);
for (int i = 0 ; i != v.size() ; i++) {
cout << v[i] << endl;
}
return 0;
}
On ideone: link.
For complex<double>
:
bool isInf(double v) {
return v== std::numeric_limits<double>::infinity()
|| -v== std::numeric_limits<double>::infinity();
}
bool isInf(complex<double> c) {
return isInf(c.real) || isInf(c.imag);
}
std::replace( array, array + N, std::complex( std::numeric_limits<double>::infinity(), 0.0), std::complex(0.0) );
std::replace( array, array + N, std::complex( -std::numeric_limits<double>::infinity(), 0.0), std::complex(0.0) );
or
bool isinf( std::complex<double> d )
{
return std::abs( d.real() ) == std::numeric_limits<double>::infinity()
}
std::replace_if( array, array + N, isinf, 0.0 );