DEV Community

Cover image for 5 Helpful Python Math Module Methods
Aya Bouchiha
Aya Bouchiha

Posted on

5 Helpful Python Math Module Methods

Hi, my name is Aya Bouchiha, today, we are going to discuss 5 methods from the math module that you will probably use in your next project!

If you are a javascript developer, I recommend to you this article:

math.floor()

math.floor(): rounds a number down to the nearest integer.

import math

print(math.floor(2.3)) # 2
print(math.floor(1.89)) # 1
print(math.floor(7.5)) # 7
print(math.floor(-10.14)) # -11
Enter fullscreen mode Exit fullscreen mode

math.ceil()

math.ceil() rounds a number up to the next largest integer.

import math

print(math.ceil(2.3)) # 3
print(math.ceil(1.89)) # 2
print(math.ceil(7.5)) # 8
print(math.ceil(-10.14)) # -10

Enter fullscreen mode Exit fullscreen mode

math.trunc()

math.trunc(): returns the integer part of a number by deleting any fractional digits.

If you're confiused with math.trunc(), math.floor() and math.ceil(), you need to know that math.trunc() plays exactly the role of math.floor() when the giving number is positive, and It play the role of math.ceil() if the giving number is negative.

import math

print(math.trunc(0.000000000000000001)) # 0
print(math.trunc(2.5)) # 2
print(math.trunc(8.999999999999999999)) # 9
print(math.trunc(-7.8)) # -7
Enter fullscreen mode Exit fullscreen mode

math.sqrt()

math.sqrt(): returns the square root of the giving positive number.

import math

print(math.sqrt(4)) # 2.0
print(math.sqrt(25)) # 5.0
print(math.sqrt(100)) # 10.0
print(math.sqrt(16)) # 4.0
Enter fullscreen mode Exit fullscreen mode

math.degrees()

math.degrees(): this method returns the degrees of a given angle in radians.

import math

pi = math.pi 

print(math.degrees(1)) # 57.29577951308232
print(math.degrees(pi)) # 180.0
print(math.degrees(pi / 2)) # 90.0
print(math.degrees(pi / 4)) # 45.0

Enter fullscreen mode Exit fullscreen mode

Reference

Hope you enjoyed reading this post, Have a nice day!

Top comments (1)

Collapse
 
aatmaj profile image
Aatmaj

You all might like to read more about math module or solve some exercises