next up previous
Next: FixedPoint Exceptions Up: FixedPoint Fixed Previous: FixedPoint Fixed


FixedPoint Rounding

The rounding algorithm used by FixedPoint when coercing floating point values to FixedPoint values can be set or re-defined by the developer to meet the requirements of the application. By default, FixedPoint objects use a type of rounding typically referred to as "Banker's Rounding" which is useful in financial applications. The available rounding algorithms include:



To change the rounding algorithm used by the FixedPoint class, set the value of the class method FixedPoint.round; e.g.,

 
>>>
>>> from fixedpoint import FixedPoint, addHalfAndChop
>>>
>>> # Demonstrate the default rounding
...  
>>> print FixedPoint("1.555")
1.56
>>> print FixedPoint("1.565")
1.56
>>> print FixedPoint("1.575")
1.58
>>> # Use a "round up" algorithm
... FixedPoint.round = addHalfAndChop
>>> 
>>> print FixedPoint("1.555")
1.56
>>> print FixedPoint("1.565")
1.57
>>> print FixedPoint("1.575")
1.58
>>> print FixedPoint("-1.555")
-1.56
>>> print FixedPoint("-1.565")
-1.57
>>> print FixedPoint("-1.575")
-1.58
>>>

Developers may customize the FixedPoint rounding algorithm by defining a newRoundingAlgorithm function as follows:



For example:

>>> from fixedpoint import FixedPoint
>>> def truncate(dividend, divisor, quotient, remainder):
...     """Don't round: truncate"""
...     return quotient
... 
>>> FixedPoint.round = truncate
>>> print FixedPoint("1.555")
1.55
>>> print FixedPoint("1.565")
1.56
>>> print FixedPoint("1.575")
1.57
>>>

Note that changing the rounding algorithm changes the algorithm for ALL new instances of FixedPoint objects including those created as the result of operations on FixedPoint objects. It is a good practice to set the rounding algorithm right after importing FixedPoint, and to avoid changing it in the body of the program.



Ganesan R 2003-08-13