How to Use Math Functions in Python


Here we will show you a list of small examples that demonstrate how to use some basic math functions in Python.

2. abs() function

The function abs(x) returns absolute value of x.

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
from math import *

print("abs(-45) : ", abs(-45))
print("abs(100.12) : ", abs(100.12))

Output:

abs(-45) :  45
abs(100.12) :  100.12

3. ceil() function

The function ceil(x) returns the smallest integer not less than x.

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
from math import *

print( "math.ceil(-45.17) : ", ceil(-45.17))
print ("math.ceil(100.12) : ", ceil(100.12))
print ("math.ceil(100.72) : ", ceil(100.72))

Output:

math.ceil(-45.17) :  -45
math.ceil(100.12) :  101
math.ceil(100.72) :  101

4. floor() function

The function floor(x) returns the largest integer not greater than x.

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
from math import *

print("math.floor(-45.17) : ", floor(-45.17))
print("math.floor(100.12) : ", floor(100.12))
print("math.floor(100.72) : ", floor(100.72))

Output:

math.floor(-45.17) :  -46
math.floor(100.12) :  100
math.floor(100.72) :  100

5. round() function

The function round(x, y) returns a floating-point number that is a rounded version of x, with y decimals.

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
from math import *

print("round(80.23456, 2) : ", round(80.23456, 2))
print("round(100.000056, 3) : ", round(100.000056, 3))
print("round(-100.000056, 3) : ", round(-100.000056, 3))

Output:

round(80.23456, 2) :  80.23
round(100.000056, 3) :  100.0
round(-100.000056, 3) :  -100.0

6. pow() function

The function pow(x, y) returns the value of x to the power of y.

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
from math import *

print("math.pow(100, -2) : ",pow(100, -2))
print("math.pow(2, 4) : ", pow(2, 4)

Output:

math.pow(100, -2) :  0.0001
math.pow(2, 4) :  16.0

7. exp() function

The function exp(x) returns exponential of x.

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
from math import *

print ("math.exp(-45.17) : ", exp(-45.17))
print ("math.exp(100.12) : ", exp(100.12))
print ("math.exp(100.72) : ", exp(100.72))

Output:

math.exp(-45.17) :  2.4150062132629406e-20
math.exp(100.12) :  3.0308436140742566e+43
math.exp(100.72) :  5.522557130248187e+43

8. More

There are many other math functions you can try by yourself. Their usage is very similar to the examples listed here.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments