整形数多次乘除运算精度损失问题
问题现象 :
计算电流时,小电流误差大,大电流误差大,刚好中间的值是准确的;
分 析 :
直接分析AD值是正常的;大概率出现在计算的精度损失上;
优化思路 : 一连串的计算可能会损失精度,因此将分子分母单独计算出来再计算最终值;
原程序计算电流 :
originCurrent=(unsigned long)(((( unsigned long long)temp1200)/(26387/200)/10)120/100)*(5000/CURRENT_SENSE_RES);
优化后:
const uint32_t divisor = 26387UL * 10UL * 100UL * (uint32_t)CURRENT_SENSE_RES;
uint64_t multiply_part = (uint64_t)temp1 * 200UL * 120UL * 5000UL * 200UL;
originCurrent = (uint32_t)(multiply_part / divisor);

浙公网安备 33010602011771号