在最近的文章Checking if a matrix contains nans or infinite values in CUDA 中,Robert Crovella 建议使用isinf()
来检查 CUDA 中的无限值。
下面我提供了一个使用isinf()
和利用 CUDA Thrust 检查数组中无限值的示例。也许它可以作为其他用户的参考。下面的例子相当于 Matlab 的d_result=isinf(d_data);
. 它与我为上面引用的问题发布的示例不同,当前一个检查每个单独的元素是无限的,而另一个检查整个数组是否包含至少一个NaN
并且等效于 Matlab 的sum(isnan(d_data));
.
#include <thrust/sequence.h>
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <thrust\device_vector.h>
#include <thrust\reduce.h>
#include <float.h>
// --- Operator for testing inf values
struct isinf_test {
__host__ __device__ bool operator()(const float a) const {
return isinf(a);
}
};
void main(){
const int N = 10;
thrust::host_vector<float> h_data(N);
for (int i=0; i<N; i++)
h_data[i] = rand()/RAND_MAX;
h_data[0] = FLT_MAX/FLT_MIN;
thrust::device_vector<float> d_data(h_data);
thrust::device_vector<float> d_result(h_data);
thrust::transform(d_data.begin(), d_data.end(), d_result.begin(), isinf_test());
for (int i=0; i<N; i++) {
float val = d_result[i];
printf("Isinf test for element number %i equal to %f\n",i,val);
}
getchar();
}