Python Numbers, Type Conversion and Mathematics



Python supports three numeric types: integers numbers, floating-point numbers, and complex numbers. They are defined as int, float, and complex classes in Python.

The difference between integers and floating points is the presence or absence of decimal point. For example, 7 is an integer, whereas 7.0 is a floating number.

Complex numbers are formulated in the form of x + yj where x is the real part and y is the imaginary part.

You can use the type() function to know which class a value or a variable belongs to and the isinstance() function to verify if it belongs to a specified class.

Let us see the following example:

x = 7
y = 7.0
z = 7 + 2j

print(type(x))
print(type(y))
print(type(z))

print(isinstance(x, int))
print(isinstance(y, float))
print(isinstance(z, complex))

The output of the above code is as follows:

<class 'int'>
<class 'float'>
<class 'complex'>
True
True
True

In Python, integers type can be of any length, but a floating-point number is accurate only up to 15 decimal places.

In addition to the decimal (base 10) number system, Python supports binary (base 2), hexadecimal (base 16), and octal (base 8) number systems.

In Python, to represent numbers in different number systems, you can just place a prefix before that number. The following table shows the corresponding prefix for each number system.

+---------------+--------------+
| Number System | Prefix       |
+---------------+--------------+
| Binary        | '0b' or '0B' |
| Octal         | '0o' or '0O' |
| Hexadecimal   | '0x' or '0X' |
+---------------+--------------+

In the following example, we will see how to write numbers in different number systems.

# Output: 109
print(0b1101101)

# Output: 165
print(0xA5)

# Output: 52
print(0o64)

After executing the above code, the output will be as follows:

109
165
52

Type Conversion

You can convert one type of number into another. In Python is called coercion.

In Python, operations like addition, subtraction coerce (force) integer to float implicitly if one of the operands is float.

>>> 4 + 6.0
10.0

As you can see above, the 4 integer is coerced into 4.0 for addition, and the result is a floating number.

You can also convert between types explicitly using the built-in functions like int(), float(), and complex().

Let us consider the following examples:

>> int(7.4)
7
>> int(-8.1)
-8
>> float(6)
6.0
>> complex("7+3j")
(7+3j)

If you convert float to integer, the number will get truncate (decimal parts will be removed).


Python Decimal

In Python, calculations using the built-in class float might produce some bizarre results than what we know. We know that the sum of 1.1 and 2.2 is 3.3, but Python seems to disagree.

>>> (1.1 + 2.2) == 3.3
False

Why is the result False?

In Python, the floating-point numbers are implemented in computer hardware as base 2 fractions. And most decimal fractions cannot be represented exactly as binary fractions. So, the decimal floating-point numbers you type are approximated by the binary floating numbers stored in the machine.

Let us see an example. You cannot represent the fraction 1/7 as a decimal number. This will give 0.142857... which is infinitely long, and you can only approximate it.

In the same way, no matter how many base 2 digits you are using, the decimal value of 0.1 cannot be represented exactly as a base 2 fraction. The decimal 0.1 will result in an infinitely long binary fraction of 0.0001100110011001... and the computer only stores a finite number of it.

It is a limitation of the computer hardware and not an error in Python.

>>> 1.1 + 2.2 
3.3000000000000003

To fix this issue, you can use the decimal module that comes with Python. The decimal module has user-settable precision compared to the floating-point numbers that have precision up to 15 decimal places.

Let us see the difference in the following example:

import decimal 

print(0.1)

print(decimal.Decimal(0.1))

Output:

0.1 
0.1000000000000000055511151231257827021181583404541015625

The decimal module is used when you want to do the standard decimal calculations that we know.

The decimal module also preserves significance, the coefficient digits do not truncate trailing zeros.

import decimal 

print(decimal.Decimal('1.1') + decimal.Decimal('2.2'))

print(decimal.Decimal('1.7') + decimal.Decimal('2.340'))

The output of the above code is as follows:

3.3 
4.040

As we can see above, the decimal module preserves the trailing zeros.

Why not use the Decimal module every time?

You might ask if the decimal module is more accurate, why not implement it every time instead of float?

The principal reason is efficiency. Python can do floating-point operations gaster than Decimal operations.

When to implement the Decimal module instead of float?

You can use the Decimal module in the following cases:

  • When you create financial applications that need exact decimal representation.
  • When you want to manage the level of precision demanded.
  • When you want to achieve the notion of significant decimal places.

Python Fractions

Python supports operations concerning fractional numbers through its fractions module.

A fraction has a numerator and a denominator, and both are integers.

The fractions module has support for rational number arithmetic.

Let us see how we can create fraction objects.

import fractions

print(fractions.Fraction(1.7))

print(fractions.Fraction(1,6))

print(fractions.Fraction(9))

Output

5/2
1/6
9

When you create Fraction from float, you might get some bizarre result. This is due to the limitations of the representation of decimal fractions as binary fractions, as explained in the previous section.

In the Fractions module, you can instantiate using numbers or strings. The preferred way is to use the instantiation with strings when using decimal numbers.

In the following example, we will see why string instantiation is the best.

import fractions

# As float 
# Output: 5404319552844595/4503599627370496 
print(fractions.Fractions(1.2))

# As float
# Output: 6/5
print(fractions.Fractions('1.2'))

The output of the above code will be:

5404319552844595/4503599627370496 
6/5

The fractions module supports all basic operations. Let us see few examples.

import fractions

print(fractions.Fraction(2,3) + fractions.Fraction(4,3) )

print(fractions.Fraction(7,2) + fractions.Fraction(3,2))

print(1 / fractions.Fraction(5,4) )

print(fractions.Fraction(2,3) > 0)

print(fractions.Fraction(-2,3) < 0)

print(fractions.Fraction(0,3) == 0)

The output will be as below:

2
5
4/5
True
True
True

Python Mathematics

Python provides modules like random and maths to support different mathematics operations like logarithms, probability, trigonometry, etc.

Let us see some examples of the math module.

import math

print(math.factorial(5))

print(math.pi)

print(math.sin(0))

print(math.cos(0))

print(math.log10(100))

print(math.exp(3))

print(math.sinh(1))

Output

120
3.141592653589793
0.0
1.0
2.0
20.085536923187668
1.1752011936438014

In the following example, we will see some functions of the random module.

import random

print(random.randrange(0, 9))

fruits = ["apple", "orange", "kiwi", "blueberry"]

# Make a random choice 
print(random.choice(fruits))

# Shuffle x
random.shuffle(fruits)

# Show the shuffled x
print(fruits)

# Show random element
print(random.random())

After running the above code, we get the following output. (Values may be different because of the random behavior)

3
blueberry
['orange', 'apple', 'blueberry', 'kiwi']
0.6275905813817293


ExpectoCode is optimized for learning. Tutorials and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 2020-2021 by ExpectoCode. All Rights Reserved.