Python: Mathematics

Numbers in Python are no different from regular numbers and support mathematical operations familiar to you from mathematics. Numeric types in Python are represented by three types: integers, floats, and complexes. Let's take a closer look at each of them.

Integers Variables and literals of this type take values from a (limited) set of integers. The integer type in Python, when necessary, is denoted as int.

Table. Arithmetic Operations for Integer Type

Operation Description
x + y sum of x and y
x - y difference between x and y
x * y product of x and y
x / y quotient of dividing x by y
x // y integer division of x by y
x % y remainder of dividing x by y
-x unary minus - returns x with the opposite sign
x ** y x raised to the power of y

Code: Example Arithmetic Operations


>>> x = 1 + 2
>>> print(x)
3

>>> x = 11 // 2
>>> print(x)
5

>>> x = 2 ** 4
>>> print(x)
16

            

Table. Basic Functions for Integer Type

Function Description
abs(x) returns the absolute value of x
int(x) returns the integer part of x
float(x) returns the floating point representation of x
divmod(x, y) returns the pair (x // y, x % y)

Code: Example Basic Functions for Integer Type


>>> x = int(9.6)
>>> x
9

>>> x = abs(-52)
>>> print (x)
52

            

Table. Operator Precedence from Highest to Lowest

Priority Operator Description
1. ** Exponentiation
2. *, /, //, % Multiplication, Division, Integer Division, Modulus
3. +, - Addition, Subtraction

The Precedence of the Unary Minus Depends on the Operation it is Used With.

Code: Example operator precedence from highest to lowest


>>> -3 ** 2
-9
>>> 3 ** -2
0.1111111111111111

            

As we can see, in the first case, the exponentiation operation is performed first, and then the unary minus is applied, while in the second case, it's the opposite.

Code: The precedence of arithmetic operations can be changed using parentheses.


>>> 2 + 2 * 2
6
>>> (2 + 2) * 2
8
    
                

Example: Find the sum of the digits of a two-digit number. Solution. Let 𝑥 be the given two-digit number, for example, 25. The sum of the digits of this number is the sum of its first and second digits: 2 + 5 = 7. The first digit of this number can be found by dividing the number 𝑥 by 10. The second digit of this number is the remainder of dividing the number 𝑥 by 10. Then the program will look like this:

Code: Solution


x = int(input("Input two-digit number: "))
first_num = x // 10 
second_num = x % 10 
suma = first_num + second_num
print("The sum of the digits of a two-digit number %d = %d" % (x, suma))
        
                    

The input operation returns a string literal. Therefore, in the first line of the program, the result of the keyboard input is converted to an integer using the int instruction.

Output:


Input two-digit number: 25
The sum of the digits of a two-digit number 25 = 7
        
                    

Shorthand operators

In Python, alongside regular assignment, there exists combined operation: assignment with arithmetic action. For convenience, let's present all operators in the form of a table:

Operator Description Example
+= Adds the value of the right operand to the variable on the left and assigns the result to the variable on the left. b += a, equivalent to b = b + a
-= Subtracts the value of the right operand from the variable on the left and assigns the result to the variable on the left. b -= a, equivalent to b = b - a
* Multiplies the variable on the left by the value of the right operand and assigns the result to the variable on the left. b *= a, equivalent to b = b * a
/= Divides the variable on the left by the value of the right operand and assigns the result to the variable on the left. b /= a, equivalent to b = b / a
%= Finds the remainder of dividing the variable on the left by the value of the right operand and assigns the result to the variable on the left. b %= a, equivalent to b = b % a
**= Raises the variable on the left to the power of the value of the right operand and assigns the result to the variable on the left. b **= a, equivalent to b = b ** a
//= Finds the integer part of dividing the variable on the left by the value of the right operand and assigns the result to the variable on the left. b //= a, equivalent to b = b // a

The math module contains additional functions for working with numbers. Using functions from the module implies its prior import. The module is imported as follows:

You can get a list of all methods in the math module using one of the following methods:


import math
print(dir(math))
print(help(math))
            
                        

Import math module


import math
            
                        
Function Description
math.ceil(a) Rounds up to the nearest integer.
math.cmp(a,b) Returns -1 if a < b, 0 if a == b, or 1 if a > b.
math.e The mathematical constant e = 2.718281...
math.exp(x) Returns e raised to the power x.
math.fabs(a) Absolute value of a number (unlike the built-in abs function, fabs always returns a float).
math.factorial(a) The factorial of a number.
math.floor(a) Rounds down to the nearest integer.
math.fmod(a,b) Returns the remainder of dividing a by b. Unlike the built-in function for finding the remainder, it always returns a float.
math.fsum(a1,a2,…,an) Returns the sum of numbers in the list.
math.log(a,[base]) Natural logarithm. If an additional base parameter is specified, calculates the corresponding logarithm.
math.log10(a) Base 10 logarithm.
math.log2(a) Base 2 logarithm.
math.max(a,b,c,…) Finds the maximum among the numbers.
math.min(a,b,c,…) Finds the minimum among the numbers.
math.pow(a,b) Raises a to the power of b (ab).
math.round(a) Rounds (requires clarification).
math.sqrt(a) Square root extraction.

Trigonometric functions

Function Description
math.cos(X) Cosine of X (X is specified in radians).
math.sin(X) Sine of X (X is specified in radians).
math.acos(X) Arc cosine of X (in radians).
math.asin(X) Arc sine of X (in radians).
math.tan(X) Tangent of X (X is specified in radians).
math.atan(X) Arc tangent of X (in radians).
math.degrees(X) Converts radians to degrees.
math.radians(X) Converts degrees to radians.
math.cosh(X) Computes the hyperbolic cosine.
math.sinh(X) Computes the hyperbolic sine.
math.tanh(X) Computes the hyperbolic tangent.
math.acosh(X) Computes the inverse hyperbolic cosine.
math.asinh(X) Computes the inverse hyperbolic sine.
math.atanh(X) Computes the inverse hyperbolic tangent.
math.pi π = 3.1415926...

Complex Numbers. cmath Module.

Python can work with complex numbers. As it is known, the square root of a negative number results in a complex number. But if you use the sqrt() function from the math library to extract the square root, you won't get a complex number.

Import cmath module


  import cmath
              
                          

Basic Functions for Complex Type

Function Description
abs(z) Absolute value of the complex number z
complex(re, im) Creation of a complex number from a pair of real numbers re and im
z.real Real part of the number z
z.imag Imaginary part of the number z
z.conjugate() Complex conjugate of z
Function Description
cmath.pi Constant π = 3.141592...
cmath.e Constant e = 2.718281...
cmath.sqrt(z) Calculates the square root of z
cmath.exp(z) Calculates the exponential function e^z
cmath.log(z) Calculates the natural logarithm ln z
cmath.log(z, a) Calculates the logarithm base a of z
cmath.log10(z) Calculates the base 10 logarithm lg z
cmath.cos(z) Calculates the cosine of z
cmath.sin(z) Calculates the sine of z
cmath.tan(z) Calculates the tangent of z
cmath.acos(z) Calculates the arccosine of z
cmath.asin(z) Calculates the arcsine of z
cmath.atan(z) Calculates the arctangent of z
cmath.cosh(z) Calculates the hyperbolic cosine of z
cmath.sinh(z) Calculates the hyperbolic sine of z
cmath.tanh(z) Calculates the hyperbolic tangent of z
cmath.phase(z) Argument (phase) of the complex number z
cmath.polar(z) Representation of the complex number z in polar coordinates
cmath.rect(r, phi) Converts a complex number with polar coordinates r, phi to algebraic form

Random number generation. random module

Random numbers are most often used when necessary test the program by trying different numbers, for example, in simulators, games. To work with random numbers, you need to import the random module

Code Output
print(random.random()) 0.5375882543375915
print(random.uniform(10, 20)) 14.448751080168986
print(random.randint(10, 20)) 16
print(random.choice('Python')) y
print(random.choice([1, 2, 'a', 'b'])) 2
print(random.choice([1, 2, 'a', 'b'])) a
print(random.choice((1, 3, 5, 'a'))) 5
print(random.randrange(10, 20, 2)) 12

import random

print(random.random())
print(random.uniform(10, 20))
print(random.randint(10, 20))
print(random.choice('Python'))
print(random.choice([1, 2, 'a', 'b']))
print(random.choice([1, 2, 'a', 'b']))
print(random.choice((1, 3, 5, 'a')))
print(random.randrange(10, 20, 2))
              
                          

Links: Python documentation


[1] Python Operators