When writing programs in our day-to-day life, we usually come across situations where we need to use a little maths to get the task done. Like other programming languages, Python provides various operators to perform basic calculations like
* for multiplication,
% for modulus, and
// for floor division.
If you are writing a program to perform specific tasks like studying periodic motion or simulating electric circuits, you will need to work with trigonometric functions as well as complex numbers. While you can't use these functions directly, you can access them by including two mathematical modules first. These modules are math and cmath.
The first one gives you access to hyperbolic, trigonometric, and logarithmic functions for real numbers, while the latter allows you to work with complex numbers. In this tutorial, I will go over all the important functions offered by these modules. Unless explicitly mentioned, all the values returned are floats.
These functions perform various arithmetic operations like calculating the floor, ceiling, or absolute value of a number using the
fabs(x) functions respectively. The function
ceil(x) will return the smallest integer that is greater than or equal to x. Similarly,
floor(x) returns the largest integer less than or equal to x. The
fabs(x) function returns the absolute value of x.
You can also perform non-trivial operations like calculating the factorial of a number using
factorial(x). A factorial is the product of an integer and all the positive integers smaller than it. It is used extensively when dealing with combinations and permutations. It can also be used to calculate the value of sine and cosine functions.
import math def getsin(x): multiplier = 1 result = 0 for i in range(1,20,2): result += multiplier*pow(x,i)/math.factorial(i) multiplier *= -1 return result getsin(math.pi/2) # returns 1.0 getsin(math.pi/4) # returns 0.7071067811865475
Another useful function in the math module is
gcd(x,y), which gives you the greatest common divisor (GCD) of two numbers x and y. When x and y are both not zero, this function returns the largest positive integer that divides both x and y. You can use it indirectly to calculate the lowest common multiple of two numbers using the following formula:
gcd(a, b) x lcm(a, b) = a x b
Here are a few of the arithmetic functions that Python offers:
import math math.ceil(1.001) # returns 2 math.floor(1.001) # returns 1 math.factorial(10) # returns 3628800 math.gcd(10,125) # returns 5 math.trunc(1.001) # returns 1 math.trunc(1.999) # returns 1
These functions relate the angles of a triangle to its sides. They have a lot of applications, including the study of triangles and the modeling of periodic phenomena like sound and light waves. Keep in mind that the angle you provide is in radians.
You can calculate
tan(x) directly using this module. However, there is no direct formula to calculate
cot(x), but their value is equal to the reciprocal of the value returned by
Instead of calculating the value of trigonometric functions at a certain angle, you can also do the inverse and calculate the angle at which they have a given value by using
Are you familiar with the Pythagorean theorem? It states that that the square of the hypotenuse (the side opposite the right angle) is equal to the sum of the squares of the other two sides. The hypotenuse is also the largest side of a right-angled triangle. The math module provides the
hypot(a, b) function to calculate the length of the hypotenuse.
import math math.sin(math.pi/4) # returns 0.7071067811865476 math.cos(math.pi) # returns -1.0 math.tan(math.pi/6) # returns 0.5773502691896257 math.hypot(12,5) # returns 13.0 math.atan(0.5773502691896257) # returns 0.5235987755982988 math.asin(0.7071067811865476) # returns 0.7853981633974484
Hyperbolic functions are analogs of trigonometric functions that are based on a hyperbola instead of a circle. In trigonometry, the points (cos b, sin b) represent the points of a unit circle. In the case of hyperbolic functions, the points (cosh b, sinh b) represent the points that form the right half of an equilateral hyperbola.
Just like the trigonometric functions, you can calculate the value of
tanh(x) directly. The rest of the values can be calculated using various relations among these three values. There are also other functions like
atanh(x), which can be used to calculate the inverse of the corresponding hyperbolic values.
import math math.sinh(math.pi) # returns 11.548739357257746 math.cosh(math.pi) # returns 11.591953275521519 math.cosh(math.pi) # returns 0.99627207622075 math.asinh(11.548739357257746) # returns 3.141592653589793 math.acosh(11.591953275521519) # returns 3.141592653589793 math.atanh(0.99627207622075) # returns 3.141592653589798
math.pi is equal to about 3.141592653589793, when we used
asinh() on the value returned by
sinh(math.pi), we got our π back.
Power and Logarithmic Functions
You will probably be dealing with powers and logarithms more often than hyperbolic or trigonometric functions. Fortunately, the math module provides a lot of functions to help us calculate logarithms.
You can use
log(x,[base]) to calculate the log of a given number x to the given base. If you leave out the optional base argument, the log of x is calculated to the base e. Here, e is a mathematical constant whose value is 2.71828182.... and it can be accessed using
math.e. By the way, Python also allows you to access another constant π using
If you want to calculate the base-2 or base-10 logarithm values, using
log10(x) will return more accurate results than
log(x, 2) and
log(x, 10). Keep in mind that there is no
log3(x) function, so you will have to keep using
log(x, 3) for calculating base-3 logarithm values. The same goes for all other bases.
If the value whose logarithm you are calculating is very close to 1, you can use
log1p signifies 1 plus. Therefore,
log(1+x) where x is close to zero. However, the results are more accurate with
You can also calculate the value of a number x raised to the power y by using
pow(x, y). Before computing the powers, this function converts both the arguments to type float. If you want the final result to be computed in exact integer powers, you should use the built-in
pow() function or the
You can also compute the square root of any given number x by using
sqrt(x), but the same thing can also be accomplished by using
import math math.exp(5) # returns 148.4131591025766 math.e**5 # returns 148.4131591025765 math.log(148.41315910257657) # returns 5.0 math.log(148.41315910257657, 2) # returns 7.213475204444817 math.log(148.41315910257657, 10) # returns 2.171472409516258 math.log(1.0000025) # returns 2.4999968749105643e-06 math.log1p(0.0000025) # returns 2.4999968750052084e-06 math.pow(12.5, 2.8) # returns 1178.5500657314767 math.pow(144, 0.5) # returns 12.0 math.sqrt(144) # returns 12.0
Complex numbers are stored internally using rectangular or Cartesian coordinates. A complex number z will be represented in Cartesian coordinates as
z = x + iy, where x represents the real part and y represents the imaginary part. Another way to represent them is by using polar coordinates.
In this case, the complex number z would be defined a combination of the modulus r and phase angle phi. The modulus r is the distance between the complex number z and the origin. The angle phi is the counterclockwise angle measured in radians from the positive x-axis to the line segment joining z and the origin.
While dealing with complex numbers, the cmath module can be of great help. The modulus of a complex number can be calculated using the built-in
abs() function, and its phase can be calculated using the
phase(z) function available in the cmath module. You can convert a complex number in rectangular form to polar form using
polar(z), which will return a pair
(r, phi), where r is
abs(z) and phi is
Similarly, you can convert a complex number in polar form to rectangular form using
rect(r, phi). The complex number returned by this function is
r * (math.cos(phi) + math.sin(phi)*1j).
import cmath cmath.polar(complex(1.0, 1.0)) # returns (1.4142135623730951, 0.7853981633974483) cmath.phase(complex(1.0, 1.0)) # returns 0.7853981633974483 abs(complex(1.0, 1.0)) # returns 1.4142135623730951
The cmath module also allows us to use regular mathematical functions with complex numbers. For example, you can calculate the square root of a complex number using
sqrt(z) or its cosine using
import cmath cmath.sqrt(complex(25.0, 25.0)) # returns (5.49342056733905+2.2754493028111367j) cmath.cos(complex(25.0, 25.0)) # returns (35685729345.58163+4764987221.458499j)
Complex numbers have a lot of applications like modelling electric circuits, fluid dynamics, and signal analysis. If you need to work on any of those things, the cmath module won't disappoint you.
All of these functions we discussed above have their specific applications. For example, you can use the
factorial(x) function to solve permutation and combination problems. You can use the trigonometric functions to resolve a vector into Cartesian coordinates. You can also use trigonometric functions to simulate periodic functions like sound and light waves.
Similarly, the curve of a rope hanging between two poles can be determined using a hyperbolic function. Since all these functions are directly available in the math module, it makes it very easy to create little programs that perform all these tasks.
I hope you enjoyed this tutorial. If you have any questions, let me know in the comments.
Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post