Creating a numeric class

We'll try to design a new kind of number. This is no easy task when Python already offers integers of indefinite precision, rational fractions, standard floats, and decimal numbers for currency calculations. There aren't many features missing from this list.

We'll define a class of scaled numbers. These are numbers that include an integer value coupled with a scaling factor. We can use these for currency calculations. For many currencies of the world, we can use a scale of 100 and do all our calculations to the nearest cent.

The advantage of scaled arithmetic is that it can be done very simply by using low-level hardware instructions. We could rewrite this module to be a C-language module and exploit hardware speed operations. The disadvantage of inventing new scaled arithmetic is that the decimal package already does a very neat job of precise decimal arithmetic.

We'll call this FixedPoint class because it will implement a kind of fixed decimal point number. The scale factor will be a simple integer, usually a power of ten. In principle, a scaling factor that's a power of two could be considerably faster, but wouldn't be ideally suited for currency.

The reason a power of two scaling factor can be faster is that we can replace value*(2**scale) with value << scale, and replace value/(2**scale) with value >> scale. The left and right shift operations are often hardware instructions that are much faster than multiplication or division.

Ideally, the scaling factor is a power of ten, but we don't explicitly enforce this. It's a relatively simple extension to track both scaling power and the scale factor that goes with the power. We might store two as the power and as the factor. We've simplified this class definition to just track the factor.

Let's see how to define FixedPoint initialization in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset