all platforms that Python runs on use the IEEE 754 double-precision standard (i.e., 64
bits), for internal representation.
[ 20 ]
This translates into a 15-digit relative accuracy.
Since this topic is of high importance for several application areas in finance, it is
sometimes necessary to ensure the exact, or at least best possible, representation of
numbers. For example, the issue can be of importance when summing over a large set of
numbers. In such a situation, a certain kind and/or magnitude of representation error
might, in aggregate, lead to significant deviations from a benchmark value.
The module decimal provides an arbitrary-precision object for floating-point numbers and
several options to address precision issues when working with such numbers:
In [ 15 ]: import decimal
from decimal import Decimal
In [ 16 ]: decimal.getcontext()
Out[16]: Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999
999, capitals=1, flags=[], traps=[Overflow, InvalidOperation, DivisionB
yZero])
In [ 17 ]: d = Decimal( 1 ) / Decimal ( 11 )
d
Out[17]: Decimal(‘0.09090909090909090909090909091’)
You can change the precision of the representation by changing the respective attribute
value of the Context object:
In [ 18 ]: decimal.getcontext().prec = 4 # lower precision than default
In [ 19 ]: e = Decimal( 1 ) / Decimal ( 11 )
e
Out[19]: Decimal(‘0.09091’)
In [ 20 ]: decimal.getcontext().prec = 50 # higher precision than default
In [ 21 ]: f = Decimal( 1 ) / Decimal ( 11 )
f
Out[21]: Decimal(‘0.090909090909090909090909090909090909090909090909091’)
If needed, the precision can in this way be adjusted to the exact problem at hand and one
can operate with floating-point objects that exhibit different degrees of accuracy:
In [ 22 ]: g = d + e + f
g
Out[22]: Decimal(‘0.27272818181818181818181818181909090909090909090909’)
ARBITRARY-PRECISION FLOATS
The module decimal provides an arbitrary-precision floating-point number object. In finance, it might sometimes
be necessary to ensure high precision and to go beyond the 64-bit double-precision standard.
Strings
Now that we can represent natural and floating-point numbers, we turn to text. The basic
data type to represent text in Python is the string. The string object has a number of
really helpful built-in methods. In fact, Python is generally considered to be a good choice
when it comes to working with text files of any kind and any size. A string object is
generally defined by single or double quotation marks or by converting another object
using the str function (i.e., using the object’s standard or user-defined string
representation):
In [ 23 ]: t = ‘this is a string object’
With regard to the built-in methods, you can, for example, capitalize the first word in this
object: