假设我有一个数组,我想乘以该数组的所有元素并将其存储在变量中。我该怎么做?我想将A中的所有元素相乘并将结果存储在S中。这样做使我为零。
thrust::device_vector<double> A(10);
thrust::sequence(A.begin(), A.end(), 1);
double S = thrust::reduce(thrust::host, A.begin(), A.end(),
0, thrust::multiplies<double>());
这里有两个问题:
thrust::host
执行策略的使用是没有意义的(实际上,如果您使用推力矢量作为输入,则没有执行策略是有意义的)。如果您实际尝试运行此代码,则可能会遇到某种segfault或运行时错误。改用基于标签的执行,即只删除第一个参数,推力将根据类型推断执行策略。thrust::reduce
in调用中的代码中的第四个参数是产品的初始值。您将其设置为0。这意味着该代码计算的任何乘积将为零。大概您希望初始值为1。解决这两个明显的问题可以使我得到:
#include <thrust/device_vector.h>
#include <thrust/reduce.h>
#include <thrust/sequence.h>
#include <iostream>
#include <iomanip>
int main()
{
thrust::device_vector<double> A(10);
thrust::sequence(A.begin(), A.end(), 1.0);
for(auto p = A.begin(); p != A.end(); ++p) {
double v = *p;
std::cout << v << std::endl;
}
double S = thrust::reduce(A.begin(), A.end(), 1.0, thrust::multiplies<double>());
std::cout << "S = " << std::fixed << std::setprecision(1) << S << std::endl;
return 0;
}
编译并运行它使我得到:
$ nvcc -std=c++11 -o prodprob prodprob.cu
$ ./prodprob
1
2
3
4
5
6
7
8
9
10
S = 3628800.0
正确答案应该是10!= 3628800,所以我认为这工作正常。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句