Cuda 有没有一种方法可以使用推力将数组中的所有元素相乘?

Cuda 有没有一种方法可以使用推力将数组中的所有元素相乘?,cuda,thrust,Cuda,Thrust,假设我有一个数组,我想将该数组的所有元素相乘,并将其存储在一个变量中。我该怎么做?我想将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, t

假设我有一个数组,我想将该数组的所有元素相乘,并将其存储在一个变量中。我该怎么做?我想将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>());

这里有两个问题:

使用推力::主机执行策略毫无意义事实上,如果使用推力向量作为输入,则执行策略没有意义。如果您真的尝试运行此代码,我会期望出现某种segfault或运行时错误。改为使用基于标记的执行,即仅删除第一个参数,并且推力将从类型推断执行策略。 代码调用中的推力::减少中的第四个参数是产品的初始值。您正在将其设置为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,因此我判断它工作正常。

这里有两个问题:

使用推力::主机执行策略毫无意义事实上,如果使用推力向量作为输入,则执行策略没有意义。如果您真的尝试运行此代码,我会期望出现某种segfault或运行时错误。改为使用基于标记的执行,即仅删除第一个参数,并且推力将从类型推断执行策略。 代码调用中的推力::减少中的第四个参数是产品的初始值。您正在将其设置为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,因此我判断它工作正常。

撇开错误且应排除的推力::主机执行策略不谈,如果将产品初始化为0,您希望得到什么值?我期望0撇开错误且应排除的推力::主机执行策略不谈,如果将产品初始化为0,您期望得到什么值?我期望0