You are here: Spin Programming Tutorial > Spin Lesson 10 > Whole and Real Numbers

Whole and Real Numbers

The Propeller is a 32-bit device and can naturally handle whole numbers as signed integers (-2,147,483,648 to 2,147,483,647) both in constants or in run-time math expressions.  However, for real numbers (those with both integer and fraction components) the compiler supports floating-point format (single-precision, IEEE-754 compliant) for constants, and there are library objects that allow for run-time floating-point math operations.

Pseudo-Real Numbers 

For handling real numbers, there are many possible techniques.  One technique is to use integer math in a way that accommodates your real values as well as the run-time expressions involved.  We call this pseudo-real numbers.

Having 32-bit integers built in to the Propeller provides us with a lot of “elbow room” for calculations.  For example, perhaps we have an equation to multiply and divide values that have 2-digit fractions, like the following:

A = B * C / D

For our example, let’s use A = 7.6 * 38.75 / 12.5 which evaluates to 23.56.

To solve this at run time, we can adjust all the equation’s values upward by 2 digits to make them all integers, perform the math and then treat the rightmost 2 digits of the result as being the fractional portion.  Multiplying each value by 100 achieves this.  Here’s the algebraic proof:

A = (B* 100) * (C * 100) / (D * 100)

A = (7.6 * 100) * (38.75 * 100) / (12.5 * 100)

A = 760 * 3875 / 1250

A = 2356

Since we multiplied all the original values by 100, we know that the final value is really 2356 / 100 = 23.56, but for most purposes we can keep it in integer form knowing that the rightmost two digits are really to the right of the decimal point.

The above solution works as long as each of the original values and each of the intermediate results never exceed the signed integer boundaries: -2,147,483,648 to 2,147,483,647.

The example presented next includes code that uses both the pseudo-real number technique as well as floating-point numbers.

Floating-Point Numbers

In many cases, expressions involving real numbers can be solved without using floating-point values and methods, such as with the pseudo-real number technique.  Since solutions like the one above tend to execute much faster and consume less memory, it is recommended that you think carefully about whether or not you really need floating-point support before you actually use it.  If you can afford the extra execution time and memory usage, floating-point support may be the best solution. 

The Propeller Tool supports floating-point constants directly.  The Propeller chip supports floating-point run-time expressions through the use of objects; ie: at run time the Spin Interpreter can only directly process integer-based expressions.

Propeller Help Version 1.1

Copyright © Parallax Inc.

5/13/2009