0

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?

Stack Over
  • 425
  • 2
  • 8
  • 18
  • As the answer says, these are the same. Depending on the context of use of this constant, there might be better ways to optimize it. – Eugene Sh. Feb 09 '15 at 15:07

2 Answers2

2

They are the same, your compiler will evaluate 0.01F/0.499F at compile-time.

There is a mistake in your constant value 0.01F/0.499F = 0.02004008016032064F.

nouney
  • 4,363
  • 19
  • 31
  • But 0.02004008016032064F is calculated through my PC and not through the microcontroller. Are you sure that the precision is the same? – Stack Over Feb 09 '15 at 15:22
  • Yes there is a mistake, the value is corrected in the first post. – Stack Over Feb 09 '15 at 15:23
  • @StackOver It depends a lot of your target-arch/compiler. The best way to know that is to test it in your env. Anyway, using the constant is maybe the safest way. – nouney Feb 09 '15 at 16:55
1

0.01F/0.499F is evaluated at compile time. 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). The quotient 0.01F/0.499F will be then within about sqrt(2)*0.5 ULP. Using 0.02004008016032064F will be within 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.

In the end, recommend coding to whatever values are used to drive the equation. e.g. If 0.01 0.499 are the value of two resistors, use those 2 values.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256