Math Functions in Python | Set 1 (numeric functions)

Python Methods and Functions

1. ceil () : — This function returns the smallest integer value greater than a number . If the number is already an integer, the same number is returned.

2. floor () : — This function returns the largest integer value less than a number . If the number is already an integer, the same number is returned.

# Python code to demonstrate how it works
# ceil () and floor ()

 
# import & quot; math & quot ; for math operations

import math

 

a = 2.3

 
# back to 2.3

print ( "The ceil of 2.3 is:" , end = "")

print (math.ceil (a))

 
# returning floor 2,3

print ( " The floor of 2.3 is: " , end = "")

print (math.floor (a))

Output:

 The ceil of 2.3 is: 3 The floor of 2.3 is: 2 

3. fabs () : — this function returns the absolute value of a number.

4. factorial () : — This function returns the factorial of a number. An error message is displayed if the number is not an integer.

# Python code to demonstrate how it works
# fabs () and factorial ()

  
# import & quot; mathematics '' for math operations

import math

 

a = - 10

 

b = 5

  
# returns an absolute value.

print ( "The absolute value of -10 is:" , end = " ")

print (math.fabs (a))

 
# returns factorial 5

print ( "The factorial of 5 is:" , end = "")

print (math.factorial (b))

Output:

 The absolute value of -10 is: 10.0 The factorial of 5 is: 120 

5. copysign (a, b) : — This function returns a number with value "a" but signed "b" . The return value is of type float.

6. gcd () : — This function is used to compute the greatest common divisor of the two numbers mentioned in its arguments. This feature works in Python 3.5 and up.

# Python code to demonstrate how it works
# copysign () and gcd ()

 
# import & quot; math & quot; for math operations

import math

 

a = - 10

b = 5.5

c = 15

d = 5

  
# return the copysigned value.

print ( "The copysigned value of -10 and 5.5 is : " , end = " ")

print (math.copysign (  5.5 , - 10 ))

 
# return lcd 15 and 5

print ( " The gcd of 5 and 15 is: " , end = " ")

print (math.gcd ( 5 , 15 ))

Output:

 The copysigned value of -10 and 5.5 is: -5.5 The gcd of 5 and 15 is: 5 

This article is updated by Manjeet Singh If you love Python.Engineering and would like to contribute, you can also write article with contribute.python.engineering or post the article [email protected] See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.





Tutorials