2012-02-20 4 views
5

점 (x, y)을 포함하는 특정 배열의 평균을 계산하려고합니다.
추력을 사용하여 (x, y) 점으로 표시된 평균 점을 찾을 수 있습니까? 또한 평균 숫자가 평균 셀을 나타내는 지 확신 할 수 없지만 각 셀에 점의 절대 위치가 포함되어있을 때 i*numColumns + j을 의미 할 때 배열을 thrust::device_vector<int>으로 나타낼 수 있습니다.
감사합니다.추력을 사용하여 int2 배열에서 평균을 계산하는 방법

+2

'int2'유형 (즉, 'a + b = {a.x + bx, a.y + by}')에 대해 더하기 연산자를 정의 할 수는 없습니까? reduce를 사용하여 입력에 대한 합계를 계산 한 다음 요소 수로 나누십시오. – talonmies

+0

Thrust 1.5 +의 람다 자리 표시자를 사용하는 경우 연산자를 사용할 수 있습니다 (아래에서 추가 답변을 참조하십시오). – harrism

답변

8
#include <iostream> 
#include <thrust/device_vector.h> 
#include <thrust/reduce.h> 

struct add_int2 { 
    __device__ 
    int2 operator()(const int2& a, const int2& b) const { 
    int2 r; 
    r.x = a.x + b.x; 
    r.y = a.y + b.y; 
    return r; 
    } 
}; 

#define N 20 

int main() 
{ 
    thrust::host_vector<int2> a(N); 
    for (unsigned i=0; i<N; ++i) { 
    a[i].x = i; 
    a[i].y = i+1; 
    } 

    thrust::device_vector<int2> b = a; 

    int2 init; 
    init.x = init.y = 0; 

    int2 ave = thrust::reduce(b.begin(), b.end(), init, add_int2()); 
    ave.x /= N; 
    ave.y /= N; 

    std::cout << ave.x << " " << ave.y << std::endl; 
    return 0; 
} 
6

Keveman의 대답은 정확합니다. 코드를 필요로하는 유용한 팁을 추가하고 싶습니다. 코멘트가 아닌 여기에 넣을 것입니다.

Thrust 1.5에는 λ placeholder가 추가되어 @ keveman의 접근 방식을 더욱 단순하게 만들 수 있습니다. 펑터 대신 을 int2으로 정의한 다음 펑터의 인스턴스를 _1 + _2 람다 자리 표시 자 식으로 바꿉니다. 명시 적 선언 인 initmake_int2() (CUDA 제공)으로 바꿀 수도 있습니다. 참고 : int2 operator+은 CUDA 코드 샘플 SDK의 "vector_math.h"헤더에 정의되어 있지만이 파일은 CUDA의 표준 부품이 아니므로이를 명확하게하기 위해 아래에 정의합니다.

#include <iostream> 
#include <thrust/device_vector.h> 
#include <thrust/reduce.h> 

using namespace thrust::placeholders; 

__device__ 
int2 operator+(const int2& a, const int2& b) { 
    return make_int2(a.x+b.x, a.y+b.y); 
} 

#define N 20 

int main() 
{ 
    thrust::host_vector<int2> a(N); 
    for (unsigned i=0; i<N; ++i) { 
    a[i].x = i; 
    a[i].y = i+1; 
    } 

    thrust::device_vector<int2> b = a; 

    int2 ave = thrust::reduce(b.begin(), b.end(), make_int2(0, 0), _1 + _2); 
    ave.x /= N; 
    ave.y /= N; 

    std::cout << ave.x << " " << ave.y << std::endl; 
    return 0; 
} 
관련 문제