## Floats and Decimals

Python provides three kinds of floating-point values: float, Decimal, and complex. Type float holds double-precision floating-point numbers whose range depends on the C (or Java) compiler Python was built with; they have limited precision and cannot be reliably compared for equality. Numbers of type float are written with a decimal point, or using scientific notation, for example, 0.0, 5.7, 8.9e-4. It is salutary to type these into IDLE:

(0.0, 5.7000000000000002, 0.00088999999999999995)

The inaccuracy is not a Python-specific problem: Computers represent floatingpoint numbers using base 2, which can represent some decimals exactly (such as 0.5) but others only approximately (such as 0.1). Furthermore, the representation uses a fixed number of bits, so there is a limit to the number of digits that can be held.

In practice this is rarely a problem since most floating-point numbers use 64 bits which is more than sufficient in most cases. But if we need high precision, Python's Decimal numbers from the decimal module can be used. These perform calculations that are accurate to the level of precision we specify (by default, to 28 decimal places) and can represent periodic numbers like 0.1 exactly; but processing is a lot slower than with normal floats. Because of their accuracy, Decimal numbers are suitable for financial calculations.

Before Decimal numbers can be used, the decimal module must be imported. The syntax for doing this is the same whether we are writing code in a .py file, or typing in IDLE as we are here:

>>> import decimal

Here we have imported the decimal module into our IDLE Shell window. (The import semantics are explained in the Importing Objects sidebar.) Integer literals can be passed to the Decimal constructor, but because Decimals are high-precision and floats are not, we cannot pass floats; instead, we must provide floating-point values as strings. For example:

>>> decimal.Decimal(19), decimal.Decimal("5.1"), decimal.Decimal("8.9e-4")

(Decimal("19"), Decimal("5.1"), Decimal("0.00089"))

The number decimal.Decimal("5.1") is held exactly; as a float it would probably be something like 5.0999999999999996. Similarly, decimal.Decimal("0.00089") would be something like 0.00088999999999999995. We can easily convert from Decimal to float, although we may lose precision by doing so:

>>> d = decimal.Decimal("1.1") >>> f = float(d) >>> f 1.1000000000000001

Python also provides complex numbers as a built-in data type. These numbers consist of a real and an imaginary component, the latter indicated by the suffix j .* For example:

>>> c = 5.4+0.8j >>> type(c) <type 'complex'>

Here we have entered a complex number (with the syntax real_part+imagin-ary_partj), and used Python's type() function to tell us what type the c is bound to.

â˜…Mathematicians use i for imaginary numbers, whereas engineers, and Python, use j.