定点化的基本原理

本文介绍了当CPU没有浮点单元(FPU)时如何优化浮点运算的方法,包括使用整数模拟浮点数进行运算和利用定点小数进行计算的具体步骤及注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CPU有三种可能的浮点数处理方式

  • Use float instructions if your CPU has a FPU. (fast)
  • Have your compiler translate floating point arithmetic to integer arithmetic. (slow)
  • Use float instructions and a CPU with no FPU. Your CPU will generate a exception (Reserved Instruction, Unimplemented Instruction or similar), and if your OS kernel includes a floating point emulator it will emulate those instructions (slowest).

那么如果没有FPU,最好将算法转移成定点来处理来提高速度,比如:

  • 用整数来模拟浮点数

其实就是线性的映射,根据数据的动态范围把浮点映射到int8, int16或int32,
比如浮点数A,a=max(abs(A)),若要把A映射成-128~127的数,需要:
A_fix = A*(127 / a) ,即A=A_fix *a / 127;
如果B也是同样的浮点数,那么
A * B = A_fix* B_fix * a * b / (127 * 127) 就转化成一个定点运算。
注意A*(127 / a) 这一步会有精度损失,A_fix* B_fix * a * b / (127 * 127)这一步有可能溢出。

  • 用定点小数来模拟浮点数

所谓定点小数,就是小数点固定的小数。可以参考这篇文章 Fixed Point Arithmetic on the ARM。可以用库libfixmath
这个库把浮点变换成Q16.16的定点小数来进行计算,并且可以变换回来。

对于Q16.16的数:
static const fix16_t fix16_one = 0x00010000;
static const fix16_t fix16_maximum = 0x7FFFFFFF;
static const fix16_t fix16_minimum = 0x80000000;
最大精度是1.525e-05, cout << fix16_to_float(0x00000001) <

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值