Math/CMath Modules - Python
Math/CMath Modules in Python
For a better reading experience, check the published document
Installation
Both math and cmath are built-in modules that come with python.
What can we do with them?
We can use "math" and "cmath" to get some popular scientific constants and methods. They also provide methods to solve some very advanced and complex equations by a single command.
NOTE: not all of the methods are mentioned in this document, but you can reach all the methods with their detailed explanation by running the following command on the CMD:
# for math module
help(math)
# for cmath module
help(cmath)
Importing the module
from math import *
from cmath import *
Popular constants
pi # returns the value of pi: 3.141592653589793
tau # returns the value of tau (2 pi): 6.283185307179586
e # returns the Euler’s number, which is (2.718)
5e23 # this is the scientefic representation of: 5*(10**23)
inf # value of infinity
-inf # value of the negative infinity
Popular methods
log(50) # regular logarithm (ln) of 50
log10(50) # tenth logarithm of 50
log(50, 10) # tenth logarithm of of 50
factorial(3) # factorial of (3), ( 3! )
floor(4.25) # floor value = 4
floor(-4.25) # floor value = 5
ceil(4.25) # ceil value = 5
ceil(-4.25) # ceil value = 4
trunc(4.25) # delete (truncate) all the decimal digits = 4
modf(5.3) # return the fractional and integer parts of the input => (0.3, 5.0)
pow(2, 3) # (2) to the power (3) , which is (8)
exp(5) # exponential to the power (5)
gcd(5, 4, 3) # Greatest Common Divisor among the tuple
lcm(5, 4, 3) # Least Common Multiple among the tuple
sqrt(100) # square root
prod([2,3,4, 8, 20]) # the product of all the elements in the iterable = 3840
radians(0.5) # convert to radian value
degrees(0.5) # convert to degree value
comb(20, 4) # number of ways to choose 4 items from 20 items without repetition or order
perm(20, 4) # number of ways to choose 4 items from 20 items without repetition but with order
isfinite(5) # check if (5) is a finite or not
isinf(5) # check if (5) is infinity or not
isclose(5, 8, abs_tol=2) # check if the (5) and (8) are close or not by the magnitude (2)
isnan(5) # check if the value is a NaN (not a number) or not
isqrt(200) # returns the integer part of the square root of the input
Trigonometric and Complex methods
# trigonometric functions
sin(30)
cos(30)
tan(30)
# inverse trigonometric functions
asin(30)
acos(30)
atan(30)
# hyperbolic trigonometric functions
sinh(30)
cosh(30)
tanh(30)
# inverse hyperbolic trigonometric functions
asinh(30)
acosh(30)
atanh(30)
# complex number (from cmath)
x = 4 + 3j
# or we can use this:
x = complex(4, 3)
Comments
Post a Comment