Python has variety of built in modules. One of the commonly used module is “math”. It has many built in functions and constants.
To use this module,
use the keyword “import”
import math
It has some constant
values that are listed below.
#This program uses
the math constants.
import math
#math.pi gives the
pi value (3.14…).
print(math.pi)
#math.e denotes
euler’s number.
print(math.e)
#math.tau
represents tau.
print(math.tau)
#math.inf gives floating
point infinity value.
print(math.inf)
#math.nan provides
floating point not a number value.
print(math.nan)
When executing
this program, the user gets the below output.
output:
3.141592653589793
2.718281828459045
6.283185307179586
inf
nan
math module’s
functions:
math module has variety of built in
functions for performing basic mathematical calculations to advanced calculations.
Here, some of the
basic mathematical functions are listed below.
math built in
functions: ceil(), floor() ,fabs():
As we know already, ceil is used to
round up the number to nearest integer. Function floor gives down to nearest
integer. ‘fabs’ returns you the absolute value.
#math function ‘ceil’, ‘floor’, ‘fabs’
import math
#ceil function round up the number.
print(math.ceil(15.6))
#floor function returns the down integer value.
print(math.floor(15.6))
#fabs gives you the exact value.
print(math.fabs(45.8))
The output of the program is
Math built in functions: factorial(), fmod(), gcd() :
Here, ‘factorial’ returns the
factorial value of the given number. ‘fmod’ gives you the reminder value. ‘gcd’
finds the greatest common factor of the given numbers.
import math
#It prints the factorial value of 6.
print(math.factorial(6))
#This line prints the reminder value of 10/3 as
floating number.
print(math.fmod(10,3))
#This statement gives you the greatest common factor
between 45 and 55.
print(math.gcd(45,55))
Output is
math built in functions :pow(),sqrt(), trunc() :
These three are the commonly
used functions. ‘pow’ is used to give the number’s multiple value. ‘sqrt’ gives
you the square root of a variable.’trunc’ returns the integer part of the
number.
import math
#This dispalys the 2*2*2*2*2 value.
print(math.pow(2,5))
# This function returns the square
root of the number 25.
print(math.sqrt(25))
#trunc returns the integer value.
print(math.trunc(56.4))
These are the basic math functions and constants used in ‘math’ module.
No comments:
Post a Comment