避免在 C 中进行浮点运算
Avoid floating point operations in C
我在嵌入式 STM32F4 项目中工作,作为限制,我只能使用整数。
我已经有了一个使用浮点数的可行解决方案。
#define TIMER_PERIOD 0.0000020833
float Get_Speed_Period(){
int tics = Get_Timer_Tics();
return tics * TIMER_PERIOD;
}
float Get_Rotation_Speed(float speed_period){
return (1 / speed_period * 64);
}
int main(){
float W = Get_Rotation_Speed ( Get_Speed_Period() );
return 0;
}
我的目标是只使用整数。我怎样才能做到这一点?
谢谢。
一个简短的说明:您可能希望使用 long long
数据类型以获得更高的存储容量(通常为 8 字节),具体取决于您计算的结果整数的大小。
但是,如果您按原样使用这些函数,您将失去一些可以在数学方面进行的优化。从功能上讲,您正在这样做:
W = (1/(tics * timerperiod) * 64)
如果您简化该数学运算(请注意,您的 64 最终出现在分子中——如果这不是您想要的,那么您需要重新构造一些),您会得到:
W = 64 * (1/timerperiod) / tics
1/timerperiod = 1/0.000020833 = 4800.7680
W = 64 * 48000.7680 / tics
W = 64 * 48000.7680 / Get_Timer_Tics();
那么您可以主要使用整数来实现它:
long long W = 64 * 48000 / Get_Timer_Tics();
请注意,我对 48000 进行了四舍五入,因为我怀疑原始值不是 48001,而浮点运算使其略有偏差。
我在嵌入式 STM32F4 项目中工作,作为限制,我只能使用整数。
我已经有了一个使用浮点数的可行解决方案。
#define TIMER_PERIOD 0.0000020833
float Get_Speed_Period(){
int tics = Get_Timer_Tics();
return tics * TIMER_PERIOD;
}
float Get_Rotation_Speed(float speed_period){
return (1 / speed_period * 64);
}
int main(){
float W = Get_Rotation_Speed ( Get_Speed_Period() );
return 0;
}
我的目标是只使用整数。我怎样才能做到这一点?
谢谢。
一个简短的说明:您可能希望使用 long long
数据类型以获得更高的存储容量(通常为 8 字节),具体取决于您计算的结果整数的大小。
但是,如果您按原样使用这些函数,您将失去一些可以在数学方面进行的优化。从功能上讲,您正在这样做:
W = (1/(tics * timerperiod) * 64)
如果您简化该数学运算(请注意,您的 64 最终出现在分子中——如果这不是您想要的,那么您需要重新构造一些),您会得到:
W = 64 * (1/timerperiod) / tics
1/timerperiod = 1/0.000020833 = 4800.7680
W = 64 * 48000.7680 / tics
W = 64 * 48000.7680 / Get_Timer_Tics();
那么您可以主要使用整数来实现它:
long long W = 64 * 48000 / Get_Timer_Tics();
请注意,我对 48000 进行了四舍五入,因为我怀疑原始值不是 48001,而浮点运算使其略有偏差。