简体   繁体   English

浮动精度

[英]Float precision

Due to precision of the microcontroller, I defined a symbol containing ratio of two flotants numbers, instead of writing the result directly. 由于微控制器的精度,我定义了一个包含两个浮点数比率的符号,而不是直接写入结果。

#define INTERVAL         (0.01F/0.499F)

instead of 代替

#define INTERVAL 0.02004008016032064F

But the first solution add an other operation "/". 但是第一个解决方案添加另一个操作“ /”。 If we reason by optimization and correct result, what is the best solution? 如果我们通过优化和正确的结果进行推理,那么最佳的解决方案是什么?

They are the same, your compiler will evaluate 0.01F/0.499F at compile-time. 它们是相同的,您的编译器将在编译时评估0.01F/0.499F

There is a mistake in your constant value 0.01F/0.499F = 0.02004008016032064F . 您的常数0.01F/0.499F = 0.02004008016032064F

0.01F/0.499F is evaluated at compile time. 在编译时评估0.01F/0.499F The precision used at compile time depends on the compiler and likely exceeds the micro-controller's. 编译时使用的精度取决于编译器,并且可能超过微控制器的精度。 Thus either approach will typically provide the same code. 因此,这两种方法通常都将提供相同的代码。

In the unlikelihood the compiler's precision is about the same as the micro-controller's float and typical binary floating-point, the values 0.01F and 0.499F will not be exact but within 0.5 ULP (unit in the last place). 不太可能的是,编译器的精度与微控制器的float和典型的二进制浮点数几乎相同, 0.01F0.499F的值将不准确,而是在0.5 ULP(最后一个单位)之内。 The quotient 0.01F/0.499F will be then within about sqrt(2)*0.5 ULP. 0.01F/0.499F将位于约sqrt(2)* 0.5 ULP之内。 Using 0.02004008016032064F will be within 0.5 ULP. 使用0.02004008016032064F将在0.5 ULP之内。 So under select situations, the constant will be better than the quotient. 因此,在特定情况下,常数将比商更好。

Under more rare circumstances, a float precision will be more than 0.02004008016032064F and the quotient would be better. 在更罕见的情况下, float精度将大于0.02004008016032064F并且商会更好。

In the end, recommend coding to whatever values are used to drive the equation. 最后,建议编码为用于驱动方程的任何值。 eg If 0.01 0.499 are the value of two resistors, use those 2 values. 例如,如果两个电阻器的电阻值为0.01 0.499 ,则使用这两个电阻器的电阻值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM