The Python Math Library provides us access to some common math functions and constants in Python, which we can use throughout our code for more complex mathematical computations. The library is a built-in Python module, therefore you don't have to do any installation to use it. In this article, we will be showing example usage of the Python Math Library's most commonly used functions and constants.
The Python Math Library contains two important constants.
The first one is Pie (π), a very popular math constant. It denotes the ratio of circumference to diameter of a circle and it has a value of 3.141592653589793. To access it, we first import the Math Library as follows:
We can then access this constant using
You can use this constant to calculate the area or circumference of a circle. The following example demonstrates this:
import math radius = 2 print('The area of a circle with a radius of 2 is:', math.pi * (radius ** 2))
The area of a circle with a radius of 2 is: 12.566370614359172
We raised the value of the radius to a power of 2 then multiplied it by pie, per the area formula of πr2.
The Euler's number (e), which is the base of natural logarithm is also defined in the Math library. We can access it as follows:
The following example demonstrates how to use the above constant:
import math print((math.e + 6 / 2) * 4.32)
Exponents and Logarithms
In this section, we will explore the Math library functions used to find different types of exponents and logarithms.
The exp() Function
The Python Math Library comes with the
exp() function that we can use to calculate the power of
e. For example, ex, which means the exponential of x. The value of
e is 2.718281828459045.
The method can be used with the following syntax:
x can be a positive or negative number. If
x is not a number, the method will return an error. Let us demonstrate the usage of this method with the help of an example:
import math # Initializing values an_int = 6 a_neg_int = -8 a_float = 2.00 # Pass the values to exp() method and print print(math.exp(an_int)) print(math.exp(a_neg_int)) print(math.exp(a_float))
403.4287934927351 0.00033546262790251185 7.38905609893065
We have declared three variables and assigned values with different numeric data types to them. We have then passed them to the
exp() method to calculate their exponents.
We can also apply this method to inbuilt constants as demonstrated below:
import math print(math.exp(math.e)) print(math.exp(math.pi))
If you pass a non-numeric value to the method, it will generate an error, as demonstrated here:
import math print(math.exp("20"))
Traceback (most recent call last): File "C:/Users/admin/mathe.py", line 3, in <module> print (math.exp("20")) TypeError: a float is required
A TypeError has been generated as shown in the above output.
The log() Function
This function returns the logarithm of the specified number. The natural logarithm is computed with respect to the base
e. The following example demonstrates the usage of this function:
import math print("math.log(10.43):", math.log(10.43)) print("math.log(20):", math.log(20)) print("math.log(math.pi):", math.log(math.pi))
In the script above, we have passed numeric values with different data types to the method. We have also calculated the natural logarithm of the
pi constant. The output looks like this:
math.log(10.43): 2.344686269012681 math.log(20): 2.995732273553991 math.log(math.pi): 1.1447298858494002
The log10() Function
This method returns the base-10 logarithm of the specified number. For example:
import math # Returns the log10 of 50 print("The log10 of 50 is:", math.log10(50))
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
The log10 of 50 is: 1.6989700043360187
The log2() Function
This function calculates the logarithm of a number to base 2. For example:
import math # Returns the log2 of 16 print("The log2 of 16 is:", math.log2(16))
The log2 of 16 is: 4.0
The log(x, y) Function
This function returns the logarithm of x with y being the base. For example:
import math # Returns the log of 3,4 print("The log 3 with base 4 is:", math.log(3, 4))
The log 3 with base 4 is: 0.6309297535714574
The log1p(x) Function
This function calculates the logarithm(1+x), as demonstrated here:
import math print("Logarithm(1+x) value of 10 is:", math.log1p(10))
Logarithm(1+x) value of 10 is: 2.3978952727983707
Arithmetic functions are used to represent numbers in various forms and perform mathematical operations on them. Some of the most common arithmetic functions are discussed below:
ceil(): returns the ceiling value of the specified number.
fabs(): returns the absolute value of the specified number.
floor(): returs the floor value of the specified number.
gcd(a, b): returns the greatest common divisor of
fsum(iterable): returns the sum of all elements in an iterable object.
expm1(): returns (e^x)-1.
exp(x)-1: when the value of x is small, calculating
exp(x)-1may lead to a significant loss in precision. The
expm1(x)can return the output in with full precision.
The following example demonstrates the use of the above functions:
import math num = -4.28 a = 14 b = 8 num_list = [10, 8.25, 75, 7.04, -86.23, -6.43, 8.4] x = 1e-4 # A small value of x print('The number is:', num) print('The floor value is:', math.floor(num)) print('The ceiling value is:', math.ceil(num)) print('The absolute value is:', math.fabs(num)) print('The GCD of a and b is: ' + str(math.gcd(a, b))) print('Sum of the list elements is: ' + str(math.fsum(num_list))) print('e^x (using function exp()) is:', math.exp(x)-1) print('e^x (using function expml()) is:', math.expm1(x))
The number is: -4.28 The floor value is: -5 The ceiling value is: -4 The absolute value is: 4.28 The GCD of a and b is: 2 Sum of the list elements is: 16.029999999999998 e^x (using function exp()) is: 0.0001000050001667141 e^x (using function expml()) is: 0.00010000500016667084
Other math functions include the following:
pow(): takes two float arguments and raises the first argument to the second argument and returns the result. For example,
pow(2,2)is equivalent to
sqrt(): returns the square root of the specified number.
These methods can be used as demonstrated below:
The Python Math module supports all the trigonometric functions. Some of them have been enlisted below:
sin(a): Returns the sine of "a" in radians
cos(a): Returns the cosine of "a" in radians
tan(a): Returns the tangent of "a" in radians
asin(a): Returns the inverse of sine. Also, there are "atan" and "acos".
degrees(a): Converts an angle "a" from radian to degrees.
radians(a): Converts angle "a" from degrees to radian.
Consider the following example:
import math angle_In_Degrees = 62 angle_In_Radians = math.radians(angle_In_Degrees) print('The value of the angle is:', angle_In_Radians) print('sin(x) is:', math.sin(angle_In_Radians)) print('tan(x) is:', math.tan(angle_In_Radians)) print('cos(x) is:', math.cos(angle_In_Radians))
The value of the angle is: 1.0821041362364843 sin(x) is: 0.8829475928589269 tan(x) is: 1.8807264653463318 cos(x) is: 0.46947156278589086
Note that we first converted the value of the angle from degrees to radians before performing the other operations.
You can convert a number from one type to another. This process is known as "coercion". Python can internally convert a number from one type to another when an expression has values of mixed types. The following example demonstrates this:
3 + 5.1
In the above example, the integer 3 has been coerced to 3.0, a float, for addition operation and the result is also a float.
However, it is sometimes necessary for you to explicitly coerce a number from one type to another in order to meet the requirements of a function parameter or an operator. This can be done using various Python's built-in functions. For example, to convert an integer to a float, we have to call the
float() function as shown below:
a = 12 b = float(a) print(b)
The integer has been converted to a float. A float can be converted to an integer as follows:
a = 12.65 b = int(a) print(b)
The float has been converted to an integer by removing the fractional part and keeping the base number. Note that when you convert a value to an int in this way, it will be truncated rather than being rounded off.
The Python Math Library provides us with functions and constants that we can use to perform arithmetic and trigonometric operations in Python. The library comes installed in Python, hence you are not required to perform any additional installation in order to be able to use it. For more info you can find the official documentation here.