An Interest In:
Web News this Week
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
- March 25, 2024
Mathematical Modules in Python: Math and Cmath
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.
Types of Functions | Example Functions |
Rounding Functions | floor() , ceil() , fabs() |
GCD and LCM | gcd() , lcm() |
Trigonometry | sin() , cos() , tan() |
Hyperbolic Functions | sinh() , cosh() , tanh() |
Exponents and Logarithms | exp() , log() , pow() , sqrt() |
Combinatorial Functions | factorial() , comb() , perm() |
Complex Numbers | cmath.polar() , cmath.sqrt() |
Rounding Functions
These functions perform various arithmetic operations like calculating the floor, ceiling, or absolute value of a number using the floor(x)
, ceil(x)
, and 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.
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.trunc(1.001) # returns 1
math.trunc(1.999) # returns 1
Greatest Common Divisor (GCD) and Least Common Multiple (LCM)
It's easy to calculate the greatest common divisor of two or more numbers in Python using the gcd()
function. Similarly, you can use the lcm()
function to calculate the least common multiple of an arbitrary number of integers.
import math
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Outputs: 2520
print(math.lcm(*numbers))
# Outputs: 232792560
print(math.lcm(*range(1, 20)))
# Outputs: 105
print(math.gcd(1470, 3885, 2940, 1575))
What if instead of calculating the GCD or LCM of a list of numbers, you want to calculate their product? The prod()
function is helpful for that.
import math
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Outputs: 3628800
print(math.prod(numbers))
# Outputs: 3628800
print(math.factorial(10))
# Outputs: 654729075
print(math.prod(range(1, 21, 2)))
Trigonometry
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 sin(x)
, cos(x)
, and tan(x)
directly using this module. However, there is no direct formula to calculate cosec(x)
, sec(x)
, and cot(x)
, but their value is equal to the reciprocal of the value returned by sin(x)
, cos(x)
, and tan(x)
respectively.
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 asin(x)
, acos(x)
, and atan(x)
.
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 also 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
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 sinh(x)
, cosh(x)
, and tanh(x)
directly. The rest of the values can be calculated using various relations among these three values. There are also other functions like asinh(x)
, acosh(x)
, and 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
Since math.pi
is equal to about 3.141592653589793, when we used asinh()
on the value returned by sinh(math.pi)
, we got our π back.
Exponents and Logarithms
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 math.pi
.
If you want to calculate the base-2 or base-10 logarithm values, using log2(x)
and 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(x)
. The 1p
in log1p
signifies 1 plus. Therefore, log1p(x)
calculates log(1+x)
where x is close to zero. However, the results are more accurate with log1p(x)
.
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 **
operator.
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 pow(x, 0.5)
.
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
Combinatorial Functions
Combinatorics is an important branch of mathematics which is useful in a variety of fields like algebra, probability and geometry. We can already use the factorial()
function in Python's math
module in order to do all our permutation and combination calculations. However, two new functions were added to the module in version 3.9 which allow us to directly calculate permutations and combinations. These are comb(n, k)
and perm(n, k)
. The first, comb(n, k)
, will calculate the number ways of choosing k items from a set of n. perm(n, k)
will calculate the number of ways k items from a set of n can be arranged. Here are some examples:
import math
# Outputs: 6435
print(math.comb(15, 7))
# Outputs: 6435.0
print(math.factorial(15)/(math.factorial(7)*math.factorial(8)))
# Outputs: 32432400
print(math.perm(15, 7))
# Outputs: 32432400.0
print(math.factorial(15)/math.factorial(8))
One more thing that I would like to mention is that the factorial()
function would accept float with integral values before version 3.9. It still does accept them but that behavior is now deprecated.
Complex Numbers
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 phase(z)
.
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 cos(z)
.
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.
Final Thoughts
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.
Original Link: https://code.tutsplus.com/tutorials/mathematical-modules-in-python-math-and-cmath--cms-26913
TutsPlus - Code
Tuts+ is a site aimed at web developers and designers offering tutorials and articles on technologies, skills and techniques to improve how you design and build websites.More About this Source Visit TutsPlus - Code