Mathematical functions in Python

math module in python provides host of mathematical functions that include trigonometrical, logarithmic,hyperbolic and special functions

Math Updated 24 Sep 2016 2 min read

Using mathematical functions is an integral part of any programming task. Python provides a host of mathematical functions. All the mathematical functions are provided through the module called "math".

The math module offers mathematical constants as well as mathematical functions. The categories of mathematical functions include basic functions, trigonometrical functions, logarithmic functions and so on.

To invoke any mathematical function either on the python interpreter console or inside a python program with extension .py, the math module needs to be imported.

python
import math

Mathematical constants from Python

pi(π)The value of Pi(π) is 3.141592653589793
eThe value of the mathematical constant e is 2.718281828459045

Frequently Used Mathematical Functions in Python

fabs(aNumber_in)Returns the absolute value of an integer or a floating point number
ceil(aNumber_in)Ceil returns next integer bigger than the given number
floor(aNumber_in)Floor returns next integer smaller than the given number
trunc(aNumber_in)Truncates a floating point number and returns the integer part
modf(aNumber_in)The number is split into to a fractional part and an integer part and the values are returned.
pow(aNumber_in, aPower_in)Returns the value of aNumber_in raised to the power aPower_in.
sqrt(aNumber_in)Returns the square root value of the given number.
gcd(aInteger1_in, aInteger2_in)Returns the greatest common devisor of two integers
degrees(aRadians_in)Converts an angular value specified in radians into degrees
radians(aDegrees_in)Converts an angular value specified in degrees into radians
hypot(aPointX_in, aPointY_in)Returns the distance between origin i.e., (0,0) and the specified point.
sin(aRadians_in)Sine theta value i.e, ratio of opposite side to the hypotenuse is returned.
cos(aRadians_in)Cos theta value i.e, ratio of adjacent side to the hypotenuse is returned.
tan(aRadians_in)Tan theta value i.e, ratio of Cos theta to the Sine theta is returned.

Example program using functions from python math module

python
import math

#Find 2 to the power 5

math.pow(2,5)

#Find square root of 32

squareRoot = math.sqrt(32)

print("Square root of 32:{}".format(squareRoot))

#Find GCD of 32, 58

integer1 = 32

integer2 = 58

gcdValue=math.gcd(32, 58)

print("GCD of numbers {} {}:{}".format(integer1,integer2,gcdValue))

#Find ceiling of 9.99

findCeilFor = 9.99

ceiling = math.ceil(findCeilFor)

print("Ceiling of {}:{}".format(findCeilFor,ceiling))

#Find floor of 100.25

findFloorFor = 100.25

floor = math.floor(100.25)

print("Floor of {}:{}".format(findFloorFor,floor))

Output

Output
Square root of 32:5.656854249492381

GCD of numbers 32 58:2

Ceiling of 9.99:10

Floor of 100.25:100