Python - Math Module
Some of the most popular mathematical functions are defined in the math module. These include trigonometric functions, representation functions, logarithmic functions, angle conversion functions, etc. In addition, two mathematical constants are also defined in this module.
Pi is a well-known mathematical constant, which is defined as the ratio of the circumference to the diameter of a circle and its value is 3.141592653589793.
>>> import math >>>math.pi 3.141592653589793
Another well-known mathematical constant defined in the math module is e. It is called Euler's number and it is a base of the natural logarithm. Its value is 2.718281828459045.
>>> import math >>> math.e 2.718281828459045
The math module contains functions for calculating various trigonometric ratios for a given angle. The functions (sin, cos, tan, etc.) need the angle in radians as an argument.
We, on the other hand, are used to express the angle in degrees. The math module presents two angle conversion functions:
radians(), to convert the angle from degrees to radians and vice versa.
For example, the following statements convert the angle of 30 degrees to radians and back (Note: π radians is equivalent to 180 degrees).
>>> import math >>> math.radians(30) 0.5235987755982988 >>> math.degrees(math.pi/6) 29.999999999999996
The following statements show
sin, cos and tan ratios for the angle of 30 degrees (0.5235987755982988 radians):
>>> import math >>> math.sin(0.5235987755982988) 0.49999999999999994 >>> math.cos(0.5235987755982988) 0.8660254037844387 >>> math.tan(0.5235987755982988) 0.5773502691896257
You may recall that
cos(30)=32 (which is
tan(30)= 13 (which is 0.
math.log() method returns the natural logarithm of a given number. The natural logarithm is calculated to the base
>>> import math >>>math.log(10) 2.302585092994046
math.log10() method returns the base-10 logarithm of the given number. It is called the standard logarithm.
>>> import math >>>math.log10(10) 1.0
math.exp() method returns a float number after raising e to the power of the given number.
In other words,
>>> import math >>>math.exp(10) 22026.465794806718
This can be verified by the exponent operator.
>>> import math >>>math.e**10 22026.465794806703
math.pow() method receives two float arguments, raises the first to the second and returns the result. In other words, pow(4,4) is equivalent to 4**4.
>>> import math >>> math.pow(2,4) 16.0 >>> 2**4 16
math.sqrt() method returns the square root of a given number.
>>> import math >>> math.sqrt(100) 10.0 >>> math.sqrt(3) 1.7320508075688772
The following two functions are called representation functions. The ceil() function approximates the given number to the smallest integer, greater than or equal to the given floating point number.
floor() function returns the largest integer less than or equal to the given number.
>>> import math >>> math.ceil(4.5867) 5 >>> math.floor(4.5687) 4
Learn more about math module on Python docs.