Monday, January 9, 2017

Mathematical Modules in Python: Math and Cmath

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.

Arithmetic 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.

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. 

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:

Here are a few of the arithmetic functions that Python offers:

Trigonometric Functions

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 provides the hypot(a, b) function to calculate the length of the hypotenuse.

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.

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.

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 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).

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).

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)

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.


No comments:

Post a Comment