Math Module in Python

Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Learn via video course

Python Certification Course: Master the essentials
Python Certification Course: Master the essentials
By Rahul Janghu
Free
star4.90
Enrolled: 1000
Python Certification Course: Master the essentials
Python Certification Course: Master the essentials
Rahul Janghu
Free
4.90
icon_usercirclecheck-01Enrolled: 1000
Start Learning

Overview

The world is full of interesting problems that have quite extensive mathematical solutions to them, be it at the time you solve your complex Mathematics homework or when you solve your weekly science quiz!

For any programming language, it is very important to have a library that would give programmers the tools for carrying out mathematical calculations like functions for basic operations like addition, subtraction, and some advanced mathematical functions like trigonometry, logarithms, exponentials, etc. in an easier & efficient manner.

Consider the case, when you are required to find the sine of some angle in the code of some big mathematical problem, then if the mathematics tools are not available in the programming language, it would be a big task for you to implement the function for calculating the sine of an angle from scratch! But do not worry, the Python math module is here for the rescue!

After reading this blog, you would learn about the various mathematical functions available in Python & how to use them in your own code.

Math Module in Python

A math module in python in simple terms is a group of python(.py) code files that can be imported into some other python program. In simple terms, consider a module as a library that has some prewritten code that could be reused in your code.

The math module in python is a standard module in python that has functions for doing some pretty simple calculations like addition (+), subtraction (-) to various high-level functions like logarithmic, exponential, trigonometric functions. It also defines some mathematical constants like π (pie),e (Euler’s number) as well.

The underlying functions of the math module are written in CPython & are efficient to the C-standard maths library.

For using the functions available in this module, import this library as follows:

Let us discuss the various numeric functions & constants available in the math library in python language:

Python Math Module’s Constants

There are a number of mathematical constants that are required from time to time for performing certain mathematical calculations. For example, you must have used a constant called π (pie) for calculating the area of a circle of radius ‘r’. A variety of constants are available in python’s math module which is as follows:

1. math.pi

It represents the mathematical constant π = 3.14159…. Example: It can be used for the calculation of the area of a circle with radius ‘radius’ as follows :

Output:

2 . math.e

It represents the mathematical constant e = 2.718281… also called the Euler’s number. It can be used in various mathematical applications where the final result has ‘e’. Example: for calculating the value of e3 + 5:

Output :

3. math.tau

It represents the mathematical constant τ = 6.28318…. It can be used in various mathematical applications where the final result has ‘τ’. Example: for calculating the value of τ3 + 5:

Output:

4. math.inf

It represents the value of floating-point infinity i.e. a very large number.

See its value :

Output:

5. math.nan

It represents floating-point NaN value which means Not a Number. See its value:

Output:

Python Math module’s Numeric Functions

The numeric functions in the math module take real numbers/integers as arguments and after doing the specified mathematical calculations, it returns a number or a boolean value.

There are a variety of functions in this catalog, like the function math.pow(x,y) that calculates the value of xy and returns it. There are a lot of operations too like finding square root, finding factorial of a number, and much more that could be done by the math module’s mathematical function. Let’s explore all of them one by one:

1. math.ceil(x)

  • Input: Real Number
  • Return Type : Integer

This function takes one number as an argument and returns the smallest integer that is greater than or equal to x. This function can be understood by the graph given below:

Math Ceil Function

For all the numbers input in the range [1,2), the output is 2. Like, math.ceil(1.6)=2, 2 is the smallest integer such that 1.6<=2. Other Example: math.ceil(-1.4)=-1 as -1 is the smallest integer such that -1.4<=-1.

Example :

Output :

Output is 3 as 3 is the smallest integer which satisfies the expression 2.6<=3.

2. math.floor(x)

  • Input : Real Number
  • Return Type : Integer

This function takes one number as an argument and returns the largest integer that is less than or equal to x. This function can be understood by the graph given below:

For all the numbers in the range [1,2) the output is 1 as shown in the graph above. Like, math.floor(1.7)=1 ,1 is the greatest integer such that 1<=1.7. Oher example: math.floor(-2.4)=-3.

Example:

Output:

Output is 2 as 2 is the largest integer such that 2<=2.6

Output:

Output is -3 as -3 is the largest integer such that -3<=-2.7

3. math.fabs(x)

  • Input : Real Number
  • Return Type : Floating-point number

This function returns the absolute value of the number given as an argument. By absolute, we mean that if the number is -3 it would become positive i.e. 3.

The number on the left side of the origin on the x-axis becomes positive i.e it gets multiplied by -1 when returned. Example, math.fabs(-2.4) = ((-1) x (-2.4)) = 2.4.

Example:

Output :

Output :

There is another inbuilt function in python known as abs(). This function works in the same way as the math.fabs() function works with the difference that abs() would return the data type of the number based on the input number given to it, i.e. it would return an integer data type number if the input argument is an integer else it would return a floating-point number if the input argument is a floating-point number.

Example :

  • abs(-1) = 1 # here -1 is integer so an integer 1 is returned

  • math.fabs(-1) = 1.0 # here irrespective of -1 being an integer floating point 1.0 is returned.

  • abs(-1.6) = 1.6 # here floating point 1.6 is returned

4. math.copysign(x,y)

  • Input: Two real numbers
  • Return Type: Floating-point number

This function takes two arguments. It returns the absolute floating value of the first argument with the sign of the second argument. Like, copysign(4,-5) would return -4.0 i.e. 4.0 taking the negative sign of -5. Another Example: math.copysign(-3,9) = 3.0 i.e. 3.0 taking the positive sign of 9.

Example:

Output:

Example :

Output :

5. math.factorial(x)

  • Input: One positive integer
  • Return Type: Positive integer

This function takes only positive integral values i.e. x>=0 as an argument. If we give any argument other than that, it would show us an error message. This function returns the factorial of the number x. Like, factorial(5)=5x4x3x2x1=120. In real life, the factorial of a number ‘n’ means the number of ways of arranging ‘n’ objects in a row. For example, if there are 3 books on a shelf namely: A, B, C, then they can be arranged in factorial(3) ways = 3x2x1 = 6 ways as shown below:

A,B,C
A,C,B
B,A,C
B,C,A
C,A,B
C,B,A

Example:

Output:

Factorial of a positive integer can also be found using a simple for loop in the following manner :

The time taken for calculating the factorial of 100000 by both the approaches are shown below:

By For-loop :

By math.factorial() function :

It can be clearly seen that the math.factorial() function is faster in terms of speed of execution than a simple for-loop approach. So, that’s why using the math module math.factorial() function is better.

6. math.fmod(x,y)

  • Input: Two real numbers x & y, y ≠ 0
  • Return Type: Floating-point number

This function takes two numbers as input and returns the floating remainder when x is divided by y. By floating-point remainder, we mean that the result is a number r = x - n*y for some integer n such that r has the same sign as the sign of x and the absolute value of r is less than the absolute value of y. For Example math.fmod(4.5 ,1.5) = 0.0 as 0.0 = 4.5 - (3.0) * (1.5). Also, math.fmod(14,4) = 2.0 as 2.0 = 14.0 - (3.0) * (4.0).

The inbuilt ‘%’ operator could also be used for finding the floating-point remainder but it is less in terms of precision than the math.fmod() function.

Example:

Output:

Example :

Output:

7. math.gcd(x,y)

  • Input: Integer numbers
  • Return Type: Integer number

This function takes two integers as input and returns the gcd i.e. the greatest common divisor of x and y. For example, math.gcd(5,25) = 5 as 5 is the greatest integer that divides both 5 and 125 together. Also, math.gcd(27,81) = 9 as 9 is the largest integer that divides both 27 & 81.

Example:

Output:

8. math.comb(n,r)

  • Input: Positive integers n and r
  • Return Type: Integer number

This function takes two positive integers as input and returns the value of nCr i.e. the number of ways of choosing r items from n items without any repetition and without any order. In terms of real life, let there be 4 books on a shelf: A B C D Then, the ways of selecting 2 books out of 4 books are as follows :

A B A C A D B C B D C D

In total there are 6 ways of selecting them without repetition. This is what the value of math.comb(4,2) = 6 means. This function would give an error when negative numbers are given as input.

Formula :

nCr=(rn)=n!r!(nr)!_nC_r = (^n_r) = \frac{n!}{r!(n-r)!}

Here, n! Means factorial(n).

Example:

Output:

Example:

Output:

9. math.frexp(x)

  • Input: Real number
  • Return Type: A Tuple containing one floating-point number & one integer ( A tuple is simply an immutable list in python)

This function takes a real number x as an argument and returns a tuple with the first value as the mantissa(floating number) and the second value as the exponent(integer) i.e. it returns a tuple (m,e) such that x = m * 2e. Here, in this expression, the floating number m is known as the mantissa and the integer e is known as the exponent.

If the argument x=0 then it returns (0.0,0). In all the other cases it returns 0.5 <= abs(m) <= 1.0 Like, math.frexp(5.0) = (0.625, 3). As, 5.0 = 0.625 * 23, here mantissa=0.625 which is in the range 0.5<=0.625<=1.0 & exponent=2 which is an integer.

Example:

Output:

In the above output, 7 can be represented as 7 = 0.875 * 23.

10. math.fsum(iterableObj)

  • Input: An iterable object containing real numbers (an object that could be traversed using a for-loop like a list in python)
  • Return Type: A floating-point number

This function takes an iterable object like a list as an argument and returns the floating-point sum of the iterable object. Like, if l=[2.1,3.2,-1.3]. Then, math.fsum(l)=4.3 as 2.1 + 3.2 + (-1.3) = 4.3.

Example:

Output:

11. math.isclose(x, y, rel_tol = 1e-09, abs_tol = 0.0)

  • Input: Two real numbers, two optional real number arguments with default value of rel_tol = 1e-09 & abs_tol = 0.0
  • Return Type: Boolean value

Here, absolute tolerance(abs_tol) is the maximum absolute error allowed in the solution & relative tolerance(rel_tol) is relative to the solution value.

This function takes two mandatory arguments x & y and two optional arguments rel_tol & abs_tol as arguments. The function returns a boolean value.

This function tells that whether x is close to y or not based on the evaluation of the given expression:

abs(x-y) <= max(rel_tol * max(abs(x) ,abs(y)), abs_tol).

It returns True if x and y are close to each other otherwise it returns False.

Like, for :

math.isclose(5.6666666666, -5.6666666667),
L.H.S = abs(5.6666666666 - 5.6666666667) => 0.0000000001
R.H.S. = max(max(0.000000001*5.6666666667),0.0) => max(0.00000000056666666667,0.0) => 0.00000000056666666667
=> 0.0000000001 <= 0.00000000056666666667 ∴ L.H.S. <= R.H.S.
=> True

So, it would give the result as True as the expression evaluated out to be true.

Example:

Output:

If we change the relative tolerance to 0.001 in the above example, then the result would evaluate out to be true.

Output:

Some special cases:

A) math.isclose(math.nan,math.nan), here nan-Not a Number

Output:

B) math.isclose(math.inf,math.inf), here inf-Infinity

Output:

12. math.isfinite(x)

  • Input: A real number
  • Return Type: Boolean value

This function takes one number x as an argument and returns False if x is either NaN(Not a Number) or infinity, otherwise, it returns true.

Example:

Output:

Example:

Output:

13. math.isinf(x)

  • Input: A real number
  • Return Type: Boolean value

This function takes a number x as an argument and returns true if x is infinite else it returns false.

Example:

Output:

Example:

Output:

14. math.isnan(x)

  • Input: A real number
  • Return Type: Boolean value

This function takes a number x as an argument and returns true if the number is NaN, i.e. not a number else it returns False.

Example:

Output:

15. math.isqrt(x)

  • Input: A non-negative integer.
  • Return Type: An integer

This function takes one non-negative integer x as an argument and returns the floor value of the exact square root of x i.e. [√x] where [] is the greatest integer function.

This could be easily understood by the function: a2 <= x, here ‘a’ is equivalent to the greatest integer. Like, math.isqrt(10) = 3 as 3 is the greatest integer such that 32 <= 10

Example:

Output:

Output is 4 as 4 is the greatest integer such that 424^2 <= 18

Output:

16. math.lcm(x,y,z….)

  • Input: Zero or more integers
  • Return type: An integer

This function takes zero or more integer arguments. It returns the L.C.M. (least common multiple) of all the arguments passed in the function. If no argument is passed in the function then 0 is returned.

Example:

Output:

Example:

Output:

17. math.ldexp(x,i)

  • Input: A real number & an integer
  • Return type: A floating-point number

This function takes a real number x & an integer i as arguments and returns the value of the expression x * 2i. Like, math.ldexp(4,5) = 4.0 * 25 = 4.0 * 32 = 128.0

Example:

Output:

Example :

Output:

18. math.modf(x)

  • Input: A real number
  • Output: A tuple(immutable list in python) consisting of two floating-point numbers

This function takes one number x as an argument and returns a tuple (f,i) where f represents the fractional part of x and i represents the integer part of x.

Like, math.modf(3, 46) would return a tuple (0.46, 3.0) as 3.46 = 3.0 + 0.46, where 3.0 is the integral part & 0.46 is the fractional part of 3.46.

Example:

Output:

19. math.nextafter(x,y)

  • Input: Two real numbers
  • Return type: A floating-point number

This function takes two numbers x and y as input and returns the next floating-value that comes after x towards y i.e. the next floating-point number that would come towards the number y on the number line.

It means that math.nextafter(4.5, 3.2) would return 4.499999 as it is the next floating-point number that would come after 4.5 towards 3.2 as 3.2 comes on the left-hand side of 4.5 if they are represented on a number line:

Math Next After Function in Python

Example:

Output:

Example :

Output:

20. math.prod(iterableObj, start = 1)

  • Input: Iterable object like a list in python, one optional argument with default value = 1
  • Output: An integer if all the numbers in the list are integers, else a floating-point number if any element of the list is a floating-point number.

This function takes one mandatory argument i.e an iterable object like a list & an optional argument start.

It returns the product of all the values starting with the start product value which is by default = 1. If there is no element in the iterable object then simply the start value is returned. To understand the start value more clearly, it is the starting value to which all the numbers would be multiplied in the list. Like if, start = 2 and list=[3,2,5], then the result is calculated like this => start * 3 * 2 * 5 = 2 * 3 * 2 * 5 = 60.

Example:

Output:

Example :

Output:

Note: This function could have also been implemented using a simple for-loop as follows :

Output

But, the math.prod() function is better in terms of efficiency if you would calculate the time of execution for both the approaches and compare them.

21. math.remainder(x,y)

  • Input: Two real numbers.
  • Return type: A floating-point number

This function takes two numbers x & y as arguments and returns the remainder of x with respect to y. It means that it returns the value v=x-n*y where n = [x/y] , here []- > greatest integer function (floor function). For example: math.remainder(4.5,1.5) = 0.0 as 0.0 = 4.5 - (3)) * (1.5), here you can see that n = [4.5/1/5] = 3. Also, math.remainder(4.7,1.5) = 0.20 as 0.20 = 4.7 - (3) * (1.5), here you can see that n = [4.7/1.5] = [3.13] = 3.

Example:

Output:

22. math.trunc(x)

  • Input: A real number
  • Return type: An integer number

This function takes a number x as an input and returns the truncated value of x to an integer. For understanding truncated value, first understand that every real number has an integral part & a fractional part. Like, 3.1426 has an integral part (i) = 3 and a fractional part (f) = 0.1426, So, math.trunc(3.1426) = 3 as the function returns the integral part.

Example:

Output:

Output is 5,as 5 is the integral part of 5.7, it takes floor value for positive numbers

Output:

23. math.pow(x, y)

  • Input: Two real numbers
  • Return type: A floating-point number

This function takes two numbers as arguments and returns the value of xy. For example : math.pow(3, 4) = 81.0 as 34 = 81.0

Example:

Output:

Note: This expression could also be evaluated using the KaTeX parse error: Expected 'EOF', got '‘' at position 1: ‘̲**’ operator i.e. x**y. But, the math.pow() function is better in terms of efficiency if you would calculate the time of execution for both the approaches and compare them.

Also read this article to learn about pow() function in python.

24. math.exp(x)

  • Input: A real number
  • Return type: A floating-point number

This function takes one number x as input and returns the value of ex, where e=2.7182.. Which is known as the base of natural logarithms or the Euler’s number.

This function is generally more accurate than simply calculating e**x.

Example:

Output:

25. math.expm1(x)

  • Input: A real number
  • Return Type: A floating-point number

This function takes one number x as input and returns the value of ex-1. This function is more accurate than the one computed by the expression math.exp(x)-1.

Example:

Output:

26. math.log(x, [b])

  • Input: A positive real number, one optional argument with the default value of ‘e’ i.e. the Euler's number
  • Return Type: A floating-point number

This function can take one or two arguments. If only one argument is provided then it returns the logarithm of the number x to the base e i.e. loge(x).

When two arguments are given to the function then it returns the logarithm of x to the base b.

Example:

Output:

Example:

Output:

27. math.log1p(x)

  • Input: A real number x such that x>-1
  • Return Type: A floating-point number

This function takes one number as an argument and returns the logarithm of (1+x) to the base e i.e. loge(1+x). This helps in the case of finding the natural logarithm when the value of x is near 0.

Example:

Output:

28. math.log2(x)

  • Input: A positive real number
  • Return Type: A floating-point number

This function takes one number as an argument and returns the logarithm of x to the base 2 i.e. log2(x). This is better than math.log(x,2) as math.log2(x) is more accurate than the former.

Example:

Output:

29. math.log10(x)

  • Input: A positive real number
  • Return Type: A floating-point number

This function takes one number as an argument and returns the logarithm of x to the base 10 i.e. log10(x). This is better than math.log(x,10) as math.log10(x) is more accurate than the former.

Example:

Output:

30. math.sqrt(x)

  • Input: A real number
  • Return Type: A floating-point number

This function takes one number as an argument and returns the square root of x i.e. √x. For example, math.sqrt(15) = 3.8729…

Example:

Output:

To know more about sqrt() function in python click here.

31. math.acos(x)

  • Input: A real number
  • Return Type: A floating-point number

This function takes one number x & returns the arc cosine of x in radians. The value returned lies between 0 & π.

To know more about arcos, refer to the link given below : https://en.wikipedia.org/wiki/Inverse_trigonometric_functions

Example:

Output:

32. math.asin(x)

  • Input: A real number
  • Return Type: A floating-point number

This function takes one number x & returns the arc sine of x in radians. The value returned lies between -π/2 & π/2.

To know more about asin refer to the link given below : https://en.wikipedia.org/wiki/Inverse_trigonometric_functions

Example:

Output:

33. math.atan(x)

  • Input: A real number
  • Return Type: A floating-point number

This function takes one number x & returns the arc tangent of x in radians. The value returned lies between -π/2 & π/2.

To know more about atan refer to the link given below : https://en.wikipedia.org/wiki/Inverse_trigonometric_functions

Example:

Output:

34. math.atan2(y,x)

  • Input: Two real numbers
  • Return Type: A floating-point number

This function takes two numbers y & x as input and returns the value of arc tangent of y/x in radians. This is different from the function math.atan(x) due to the fact that it knows the sign of both x & y and can then determine in which quadrant was the resultant angle of arctangent of y/x lies. To clarify this statement, consider math.atan(1), it would give result as π/4 as it considers the point (1,1) for finding the angle, but if we give the input as math.atan2(-1,-1), although -1/-1 = 1 but the point (-1,-1) lies in the third quadrant & the answer of the angle should have been -3π/4. So, math.atan(-1,-1) = -3π/4. Similarly, math.atan2(1,-1) = -π/4 as (1,-1) lies in the fourth quadrant. See the image below for more clarity:

Math ATAN Function in Python

Example:

Output:

35. math.sin(x)

  • Input: A real number
  • Return Type: A floating-point number

This function takes one number x in radians as input and returns the sine of x.

Example:

Output:

36. math.cos(x)

  • Input: A real number
  • Return Type: A floating-point number

This function takes one number x in radians as input and returns the cosine of x.

Example:

Output:

37. math.tan(x)

  • Input: A real number
  • Return Type: A floating-point number

This function takes one number x in radians as input and returns the tangent of x. Example:

Output:

38. math.degrees(x)

  • Input: A real number
  • Return Type: A floating-point number

This function takes one number x in radians as input and returns the converted value of x in degrees. Like, math.degrees(math.pi) = 180.0. Here math.pi = π & the value value of math.pi in radians = 180.0

Example:

Output:

39. math.radians(x)

  • Input: A real number
  • Return Type: A floating-point number

This function takes one number x in degrees as input and returns the converted value of x in radians. Like, math.radians(180.0) = 3.14… as 180.0 degrees equal 3.14.. In radians.

Example:

Output:

40. math.dist(x,y)

  • Input: Two iterable objects in python like a list in the python-the length of the lists should be the same
  • Return Type: A floating-point number

This function takes an iterable list of coordinates x & y and returns the Euclidean distance between x & y. Euclidean distance formula : If the two lists are l1 = [a1,b1,c1] & l2 = [a2,b2,c2] then, euclidean distance = √((a1-a2)2 + (b1-b2)2 + (c1-c2)2) Say, if x=[3,4] & y=[1,2] then, math.dist(x,y) = √((3-1)2+(4-2)2) = √(4+4) = √8 = 2.82842712475.

Example:

Output:

41. math.hypot(perpendicular,base)

  • Input: Two real numbers
  • Return Type: A floating-point number

This function takes two inputs i.e. perpendicular and base of a right-angled triangle & it returns the hypotenuse of the right-angled triangle using the Pythagorean theorem.

(hypotenuse)2 = (perpendicular)2 + (base)2 .

Example:

Output:

42. math.acosh(x)

  • Input: A real number
  • Return Type: A floating-point number

This function returns the inverse hyperbolic cosine of the argument x.

Example:

Output:

43. math.asinh(x)

  • Input: A real number
  • Return Type: A floating-point number

This function returns the inverse hyperbolic sine of the argument x.

Example:

Output:

44. math.atanh(x)

  • Input: A real number
  • Return Type: A floating-point number

This function returns the inverse hyperbolic tangent of the argument x.

Example:

Output:

45. math.cosh(x)

  • Input: A real number
  • Return Type: A floating-point number

This function returns the hyperbolic cosine of the argument x.

Example:

Output:

46. math.sinh(x)

  • Input: A real number
  • Return Type: A floating-point number

This function returns the hyperbolic sine of the argument x.

Example:

Output:

47. math.tanh(x)

  • Input: A real number
  • Return Type: A floating-point number

This function returns the hyperbolic tangent of the argument x.

Example:

Output:

48. math.erf(x)

  • Input: A real number
  • Return Type: A floating-point number

This function takes a number x as an argument and returns a value between -1 and 1 which is the error function of x. For more information about error function, see this: https://en.wikipedia.org/wiki/Error_function

Example:

Output:

49. math.erfc(x)

  • Input: A real number
  • Return Type: A floating-point number

This function takes a number x as an argument and returns the complement of the error function of x i.e. 1-math.erf(x).

Example:

Output:

50. math.gamma(x)

  • Input: A real number
  • Return Type: A floating-point number

This function takes one number x as an argument and returns the value of the gamma function of x. For more about gamma function, refer this: https://en.wikipedia.org/wiki/Gamma_function

Example:

Output:

51. math.lgamma(x)

  • Input: A real number
  • Return Type: A floating-point number

This function takes one number x as an argument and returns the logarithm of the absolute value of the gamma function of x with base e.

Example:

Output:

Comparison between math module and numpy module in Python

Math ModuleNumPy Module
It is a built-in python module.It’s an external module developed by a third party.
Can be used for performing calculations on scalar data like a list which has only one row.Can be used for performing calculations on scalar data as well as matrices having a large number of rows and columns.
Less efficient than the NumPy module as operations on a matrix require a for-loop as a matrix contains more than one row and for each row operation a for-loop would be required.Very efficient matrix operations as NumPy library incorporate the use of different processors for performing calculations.

Conclusion

  1. Using the math modules functions is more accurate than using conventional operators like 2**6.
  2. Some math module functions have very high accuracy and precision in their results.
  3. It is better to use math module functions as they are highly optimized for getting faster results.
  4. These math module functions can be used in your engineering project or some big neural networks model or in any place where high precision results are required in less time.

Also to learn about math.ceil() in Python, Click here