玩转 ArrayFire:04 初识 array(一)


前言

在《玩转 ArrayFire:03 第一个 ArrayFire 程序》中,我们已经创建第一个 ArrayFire 程序,然而却没有深入了解 ArrayFire 的用法,在这一篇中,我们将继续学习 ArrayFire 的具体用法。


一、array 支持的数据类型

     ArrayFire 提供了一个通用的容器对象,在 array 上执行函数和数学操作。该数组 array 可以表示许多不同的基本数据类型,如下表。并且,除非另外指定,否则数组的默认数据类型是 f32 (实单精度浮点数)。

f32 实单精度浮点数 float
c32 复单精度浮点数 cfloat
f64 实双精度浮点数 double
c64 复双精度浮点数 cdouble
b8 8位布尔值 bool
s32 32位有符号整数 int
u32 32位无符号整数 unsigned
u8 8位无符号整数 unsigned char
s64 4位有符号整数 intl
s16 6位有符号整数 short
u16 16位无符号整数 unsigned short

二、创建并填充 array

     array 表示存储在设备上的内存。因此,创建和填充数组将消耗设备上的内存,这些内存只有在数组对象超出作用域时才能释放。由于设备内存分配可能是昂贵的,ArrayFire还包括一个内存管理器,它将在任何可能的情况下重用设备内存。
    当需要使用数组类型时,便可以创建 array 。下面我们展示了如何使用未初始化值创建1D、2D和3D数组:

    // Arrays may be created using the af::array constructor and dimensioned
    // as 1D, 2D, 3D; however, the values in these arrays will be undefined
    array undefined_1D(100);        // 1D array with 100 elements
    array undefined_2D(10, 100);    // 2D array of size 10 x 100
    array undefined_3D(10, 10, 10); // 3D array of size 10 x 10 x 10

    但是,未初始化的内存在应用程序中可能没有用处。ArrayFire 提供了几个方便的函数来创建包含预填充值的数组,包括常量、均匀随机数、均匀正态分布数和单位矩阵:

    // Generate an array of size three filled with zeros.
    // If no data type is specified, ArrayFire defaults to f32.
    // The af::constant function generates the data on the device.
    array zeros      = constant(0, 3);
    // Generate a 1x4 array of uniformly distributed [0,1] random numbers
    // The af::randu function generates the data on the device.
    array rand1      = randu(1, 4);
    // Generate a 2x2 array (or matrix, if you prefer) of random numbers
    // sampled from a normal distribution.
    // The af::randn function generates data on the device.
    array rand2      = randn(2, 2);
    // Generate a 3x3 identity matrix. The data is generated on the device.
    array iden       = af::identity(3, 3);
    // Lastly, create a 2x1 array (column vector) of uniformly distributed
    // 32-bit complex numbers (c32 data type):
    array randcplx   = randu(2, 1, c32);

     array 也可以用主机上的

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值