# Python Numbers, Type Conversion and Mathematics

## Python Numbers, Type Conversion and Mathematics

In this section we will learn about the numbers that are used in Python. We will also learn the conversion from one data type to other and the operations that can be performed in Python.

The numbers that are supported by Python are integers, floating point numbers and complex numbers. The integers are those that do not have any decimal part or fraction, floating point numbers include decimal fraction and complex numbers are those that have an imaginary part. Integers are represented as int, floating point numbers are represented as float and complex numbers are represented by complex in Python.

In Python complex numbers are written as x + yj, here x is the real part and yj is the imaginary part.

In Python the type () function is used to determine the data type of a variable. The type () function indicates that to which class the value or a variable belongs. There is another function that is named as isinstance (). The isinstance () function is used to check that if a variable or a value belongs to a particular class or not. This function returns a True or a False.

Consider the following example, in which we used the type () function to determine the class of a value:

CODE

>>> x = 4

>>> print(type(x))

>>> x = 4.5

>>> print(type(x))

>>> y = 4+2j

>>> print(y)

>>> print(isinstance(y, complex))

OUTPUT

<class ‘int’>

<class ‘float’>

(4+2j)

True In the above example the class of the variable x is checked. At first x is assigned an integer type value that is 4 and then we used the type () function to determine the class of x and got the output that the variable x is of integer type same is the case when we assigned a floating point value to the variable x and when its class is determined using the type () function we got the output float.

Then we declared another variable named y that is assigned a complex number, the number is printed and we used the isinstance () function to check either it is a complex number or not. This function returns either True or False.

In Python the integer type numbers can be of any size but the floating point numbers should be 15 places after the decimal point for accuracy. The 16th will be inaccurate.

In everyday life we use numbers that have base 10 that is these numbers are decimal numbers, but our computer understands binary, octal or hexadecimal numbers therefore, the programmers have to convert the decimal numbers into binary, octal and hexadecimal numbers.

In Python the binary, octal and hexadecimal numbers can be represented by using prefixes before the number that the user wants to convert to. The following are the prefixes that can be used before a number in Python:

 Base Prefix Binary (base 2) ‘0b’ or ‘0B’ Octal (base 8) ‘0o’ or ‘0O’ Hexadecimal (base 16) ‘0x’ or ‘0X’

Consider the following example, in which we have used the above concept of converting the bases of numbers.

CODE

>>> print (0b011101)

>>> print (0o34)

OUTPUT

29

176

28 In the above example, we used the print statement in which prefixes are used to convert the binary, octal and hexadecimal into decimal numbers.

### Type Conversion

By type conversion we mean to convert a number of one data types to another data type. To convert a data type to another data type is known as coercion. The data types of the values can be converted to other data types in Python by using the functions int (), float () and complex ().

The Python interpreter can also change the data types of the numbers implicitly.

Implicit type casting is performed automatically by the interpreter of Python. If the data types of operands or variables or values in the expression are different, the values with lower data types is converted into higher data type.

Different types of variables are as follows: EXAMPLE

Suppose x is an integer variable and y is a long variable and the following expression is evaluated:

x + y;

In the above expression, data type of x is lower than the data type of y. So the value of x will be converted into long during the evaluation of expression. The data type of x is not changed. Only the data type of the value of x is changed during the evaluation of the expression.

Consider the following example in which an integer type number and a floating point number are added. The integer will be converted to float and then addition will be performed:

CODE

>>> 2+4.0

OUTPUT

6.0 In the above example, 2 is converted to floating point number that is 2.0 so that it can be added to the floating point number. It can be seen in the above example that the resulted number is a floating point number.

In Python we can also use the built in functions such as int (), float (), and complex () to convert the data types. Consider the following example in which we have converted the data types using these functions:

CODE

>>> int(4.6)

>>> int(-4.6)

>>> float(7)

>>> complex(‘2+6j’)

OUTPUT

4

-4

7.0

(2+6j) When the number is converted from float to integer data type the number is truncated.

### Python Decimal

By using the built in Python class float we can do a lot of things that might seem amazing. As we know that 2.2 + 1.1 is equal to 3.3 but Python will disagree with this decision, consider the following example:

CODE

>>> (2.2+1.1) = =3.3

OUTPUT

False The Python interpreter reveals that the floating point numbers in the computer hardware are treated as the binary fractions because the computer only understands 0 or 1. Because of this reason the computer cannot accurately store most of the decimal numbers.

Consider an example that 1/3 cannot be written as a decimal number in computer because it results in an infinitely long number and hence our computer will store only the approximate value. So we can say that this is a limitation of the computer and not an error in the Python or Python interpreter.

This issue can be overcome by using one of the built in modules of Python. As we all know that the Python interpreter can store or calculate only up to 15 decimal places but we can settle the precision defined by us by using the Python built in modules.

Consider the following example in which used the import keyword to import the Python module named decimal which will help us define our own precision:

CODE

>>> import decimal

>>> print (0.3)

>>> print (decimal.Decimal(0.3))

OUTPUT

0.3

0.299999999999999988897769753748434595763683319091796875 In the above example a module named decimal is imported and when we printed the value without using the module the number is printed as it is. And we used the module we got the accurate precision.

By using the decimal module we can calculate the decimal numbers more accurately up to most significant figures. For example 3.50 will be more accurate than 3.5 because 3.50 has more significant figures.

Consider the following example:

CODE

>>> from decimal import Decimal as d

>>> print(d(‘2.2’)+d(‘1.1’))

>>> print(d(‘2.50’)*d(‘1.2’))

OUTPUT

3.3

3.000 In the above example, we imported Decimal from the module decimal and named it as d. In the second line of code we simply added two floating point numbers and got the output. Similarly in the third line of the code the result is printed after multiplying the floating point numbers and we got the accurate output that is up to most significant figure.

The decimal operations are not mostly used because it slows the working where as floating point operations are carried out faster.

### When to use decimal instead of float?

The decimal operations are used when:

1. We need the answer in most significant figures.
2. We want a number of precisions.
3. When we need the exact representation of the decimals.
4. Decimal operations are used to carry out floating point numbers that have more decimal places.

### Python Fractions

In Python there is a built in module name fractions which is used to perform the operations that involve fractional numbers. The fraction module supports the rational number, a rational number is that that has a denominator and a numerator both of these are integers.

A decimal number can be converted into fraction by using the fraction module. Consider the following example in which we have converted various floating point numbers into fractions:

CODE

>>> import fractions

>>> print (fractions. Fraction (2.5))

>>> print (fractions. Fraction (7))

>>> print (fractions. Fraction (3, 7))

OUTPUT

5/2

7

3/7 In the above example, the module fractions is imported and the first number that is 2.5 is converted to fraction, in the second print statement as 7 cannot be changed into fraction because it has not a decimal point or it is not in fraction. In the third print statement we used a comma between the numbers and the numbers are printed in a fraction.

If we use the float operation while converting a floating point number to fraction we might get unexpected results because the system represents imperfect binary fractions.

By using the fractions module we can also represent the strings. This is done when we are using the decimal numbers. Consider the following example:

CODE

>>> import fractions

>>> print (fractions. Fraction (2.1))

>>> print (fractions. Fraction (‘2.2’))

OUTPUT

4728779608739021/2251799813685248

11/5 In the above example, it can be seen that a large fraction is obtained when we converted the decimal point number to a fraction, this shows the accuracy by the module fraction. In the second print statement we used the floating point number as a string and got the corresponding output.

Consider the following example in which various operations are performed on various different types of fractions:

CODE

>>> from fractions import Fraction as f

>>> print (f (2, 3) +f (2, 3))

>>> print (1/f (2, 3))

>>> print (f (-2, 3) >0)

>>> print (f (-2, 3) <0)

OUTPUT

4/3

3/2

False

True In the above example, we imported Fraction from the module fractions and named it as f. In the first print statement two fractions are added and the result is printed. In the second print statement we divided one by a fraction and the result is printed. In the third print statement a fraction is checked if it is greater than 0 then the interpreter should return a true but the condition is false therefore, the interpreter is returning false. The fourth print statement is the same but it checks the expression that if the expression is smaller than 0 then the interpreter should return true.

### Python Mathematics

In Python there are built in modules such as math and random that are used to perform different operations that may include logarithms, stats and probability and the trigonometry functions.

### Python Math Module

Consider the following example, in which we have imported the math module and used different function in it:

CODE

>>> import math

>>> print (math. pi)

>>> print (math. cos (60))

>>> print (math. cos (math.pi))

>>> print (math. exp (10))

>>> print (math. log10 (1000))

>>> print (math. sinh (1))

>>> print (math. factorial (4))

OUTPUT

3.141592653589793

-0.9524129804151563

-1.0

22026.465794806718

3.0

1.1752011936438014

24 In the above example, the built in math module is imported. In the first print statement, the value of pi is printed. In the second print statement the values of cosine of 60 is evaluated and then printed. In the third print statement the value of cosine of pi is evaluated and then printed.

In the fourth print statement the exponential function is used, the value of e is 2.71828 and the expression evaluates 2.71828 raise to the power 10 and the result is printed. In the fourth print statement we evaluated log to the base 10 of 1000, the result is evaluated and printed.

In the fifth print statement the sinh function that is hyperbolic sin function is used to evaluate sinh of 1 and the result is printed. In the sixth print statement the factorial function is used to calculate the factorial of 4 and the result is printed on the output screen.

### Python random module

The random module is used to generate or pick a random from a range of values or from a list etc. Consider the following example in which the concept of random module is cleared:

CODE

>>> import random

>>> print (random. randrange (5,20))

>>> a = [‘x’, ‘y’, ‘z’, ‘q’, ‘w’]

>>> print (random. choice (a))

>>> random. shuffle (a)

>>> print (a)

>>> print (random. random ())

OUTPUT

16

y

[‘q’, ‘w’, ‘y’, ‘x’, ‘z’]

0.7975459685986384 In the above example, we imported the Python random module. In the first print statement random module is used to pick up a random number from the range 5 to 20. Before the second print statement we declared ‘a’ and in the print statement we used the choice function defined in the random module to pick up any character and display it.

In the third print statement we used the shuffle function defined in the module random to shuffle the values in the variable ‘a’ and the shuffled list is printed. In the fourth print statement we used the random function defined in random module to print a random element.