Skip to content

Cast(float转half/int32_t)

产品支持情况

  • Ascend 950PR/Ascend 950DT:支持
  • Atlas A3 训练系列产品/Atlas A3 推理系列产品:支持
  • Atlas A2 训练系列产品/Atlas A2 推理系列产品:支持
  • Atlas 200I/500 A2 推理产品:不支持
  • Atlas 推理系列产品AI Core:支持
  • Atlas 推理系列产品Vector Core:不支持
  • Atlas 训练系列产品:不支持
  • Kirin X90:支持
  • Kirin 9030:支持

功能说明

头文件路径为:"basic_api/kernel_operator_scalar_intf.h"

对标量的数据类型进行转换。

在使用该接口之前,用户需要先了解内置数据类型精度转换

函数原型

C++
template <typename T, typename U, RoundMode roundMode>
__aicore__ inline U Cast(T valueIn)

参数说明

表1 模板参数说明

参数名描述
TvalueIn的数据类型。
U转换后的数据类型。
roundMode精度转换处理模式,类型是RoundMode。
RoundMode为枚举类型,用以控制精度转换处理模式,参考精度舍入模式,可取值为:
• CAST_NONE:当转换过程存在精度损失时,按CAST_RINT模式处理;当不存在精度损失时,不进行舍入;
• CAST_RINT:向最近的偶数舍入;
• CAST_FLOOR:向负无穷大方向舍入;
• CAST_CEIL:向正无穷大方向舍入;
• CAST_ROUND:四舍五入;
• CAST_TRUNC:截断模式;
• CAST_ODD:向最近的奇数舍入。

表2 参数说明

参数名称输入/输出描述
valueIn输入被转换数据类型的标量。

数据类型

支持的数据类型如下:

  • valueIn支持float。
  • 返回值支持half、int32_t。

返回值说明

转换后的U类型标量数据。

约束说明

支持的数据类型组合及对应支持的RoundMode如下:

valueIn返回值RoundMode
floathalfCAST_ODD
floatint32_tCAST_ROUND
floatint32_tCAST_CEIL
floatint32_tCAST_FLOOR
floatint32_tCAST_RINT

调用示例

C++
float valueIn = 3.14159f;
half halfOut = AscendC::Cast<float, half, AscendC::RoundMode::CAST_ODD>(valueIn);             // 返回3.142578

valueIn = 1.5f;
int32_t intRoundOut = AscendC::Cast<float, int32_t, AscendC::RoundMode::CAST_ROUND>(valueIn); // 使用CAST_ROUND模式,四舍五入返回2
int32_t intCeilOut = AscendC::Cast<float, int32_t, AscendC::RoundMode::CAST_CEIL>(valueIn);   // 使用CAST_CEIL模式,向上取整返回2
int32_t intFloorOut = AscendC::Cast<float, int32_t, AscendC::RoundMode::CAST_FLOOR>(valueIn); // 使用CAST_FLOOR模式,向下取整返回1
int32_t intRintOut = AscendC::Cast<float, int32_t, AscendC::RoundMode::CAST_RINT>(valueIn);   // 使用CAST_RINT模式,1.5向临近偶数舍入返回2

valueIn = 2.5f;
intRoundOut = AscendC::Cast<float, int32_t, AscendC::RoundMode::CAST_ROUND>(valueIn); // 使用CAST_ROUND模式,四舍五入返回3
intCeilOut = AscendC::Cast<float, int32_t, AscendC::RoundMode::CAST_CEIL>(valueIn);   // 使用CAST_CEIL模式,向上取整返回3
intFloorOut = AscendC::Cast<float, int32_t, AscendC::RoundMode::CAST_FLOOR>(valueIn); // 使用CAST_FLOOR模式,向下取整返回2
intRintOut = AscendC::Cast<float, int32_t, AscendC::RoundMode::CAST_RINT>(valueIn);   // 使用CAST_RINT模式,2.5向临近偶数舍入返回2

免责声明:本站内容由 asc-devkit 仓 master 分支自动编译生成,属于持续开发版本,可能存在缺陷,仅供预览与参考。如需稳定及商用资料,请查阅官方 昇腾社区