东方耀AI技术分享

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
热搜: 活动 交友 discuz
查看: 1977|回复: 0
打印 上一主题 下一主题

[C/C++] 求两个向量的内积inner_product(thrust版)

[复制链接]

1365

主题

1856

帖子

1万

积分

管理员

Rank: 10Rank: 10Rank: 10

积分
14446
QQ
跳转到指定楼层
楼主
发表于 2021-7-7 11:40:32 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式







求两个向量的内积inner_product(thrust版)




  1. #include <thrust/inner_product.h>
  2. #include <thrust/device_vector.h>

  3. #include <iostream>

  4. using namespace std;

  5. //求两个向量的内积inner_product(thrust版)
  6. int main(){
  7.     thrust::device_vector<int> v1,v2(7);   //注意这个细节
  8.     //thrust::sequence(v1.begin(), v1.end());
  9.     for(int i=0;i<5;i++){
  10.         v1.push_back(i+1);
  11.     }
  12.     v2[0] = 4;
  13.     v2[1] = 3;
  14.     v2[2] = 2;
  15.     v2[3] = 1;
  16.     v2[4] = 0;
  17.     v2[5] = 5;
  18.     v2[6] = 6;
  19.     cout << "数组初始值v1:" << endl;
  20.     thrust::copy(v1.begin(), v1.end(), std::ostream_iterator<int>(std::cout, "\n"));
  21.     cout << "数组初始值v2:" << endl;
  22.     thrust::copy(v2.begin(), v2.end(), std::ostream_iterator<int>(std::cout, "\n"));

  23.     //int inner_d1_d2 = std::inner_product(d1.begin(),d1.end(),d2.begin(), 1);
  24.     int inner_d1_d2 = thrust::inner_product(v1.begin(),v1.end(),v2.begin(), 1);
  25.     //结果=1 + 1*4 + 2*3 + 3*2 + 4*1 + 5*0    = 21 对的
  26.     cout<<"v1与v2的内积(1)="<<inner_d1_d2<<endl;

  27.     //inner_d1_d2 = std::inner_product(d1.begin(),d1.end(),d2.begin(), 3,multiplies<int>(),plus<int>());
  28.     ////应用指定的二元操作,使用第一个操作代替加而第二个操作代替乘
  29.     inner_d1_d2 = thrust::inner_product(v1.begin(),v1.end(),v2.begin(), 3,thrust::multiplies<int>(),thrust::plus<int>());
  30.     //结果=3 * (1+4) * (2+3) * (3+2) * (4+1) * (5+0)   = 9375 对的
  31.     cout<<"v1与v2的内积(3)="<<inner_d1_d2<<endl;

  32.    

  33.     return 0;
  34. }

  35. /*
  36. 数组初始值v1:
  37. 1
  38. 2
  39. 3
  40. 4
  41. 5
  42. 数组初始值v2:
  43. 4
  44. 3
  45. 2
  46. 1
  47. 0
  48. 5
  49. 6
  50. v1与v2的内积(1)=21
  51. v1与v2的内积(3)=9375

  52. */



复制代码


让天下人人学会人工智能!人工智能的前景一片大好!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|人工智能工程师的摇篮 ( 湘ICP备2020019608号-1 )

GMT+8, 2024-6-3 17:57 , Processed in 0.224581 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表