Nowadays, most embedded systems are built using 32-bit CPUs. These devices give plenty of scope for performing the arithmetical processing required for various applications. Calculations can be performed on signed or unsigned integers and 32 bits gives a good range of values: +/- 2 billion or up to 4 billion respectively. Extending to 64 bits is reasonably straightforward.
If you need to stray outside of these ranges of values or perform more sophisticated operations, then you need to think in terms of floating point and this presents a range of new challenges …
The concept of a floating point number is simple enough – the value is stored as two integers: the mantissa and the exponent. The number represented is the mantissa multiplies by 2 to the power of the exponent. Typically, these two integers are stored in bit fields in a 32-bit word, but higher precision variants are also available. The most common format is IEEE 754-1985.
The clear benefit of using floating point is the wide range of values that may be represented, but this comes at a cost:
Performance. Floating point operations take a lot of time compared with integers. If the processing is done in software, the execution time can be very long indeed. Hardware floating point units speed up operations to a reasonable extent.
Precision. Because of the way that values are represented in floating point, a value may not be exactly what you expect. For example, you may anticipate a variable having the value 5.0, but it actually is 4.999999 This need not be a problem, but care is needed in coding with floating point.
Obviously, code like this would be foolish:
if (x == 3.0)
as x may never be precisely 3.0
Similarly, coding a loop like this might produce unexpected results:
for (x=0.0; x<5.0; x++)
You would expect the loop to be performed 5 times for x values 0.0, 1.0. 2.0, 3.0 and 4.0 This might work, but it is quite possible that an extra iteration will occur for x being 4.999999
The solution is to use an integer loop counter:
for (i=0,x=0.0; i<5; i++,x++)
Broadly speaking, floating point should only be used if it is essential and only after every creative way to do the calculations using integers has been investigated and eliminated.
Posted August 28th, 2012, by Colin Walls
- Change is good
- Article: floating point in embedded systems
- Moving to Mac – an update
- Embedded systems – an identity crisis?
- The work/life balance (or lack thereof) and why am I so busy?
- Articles about power management and RTOS memory utilization
- Six of the best: beers
- Video blog – using software IP
- What if? How history could have been different
- An update on bottle sizes