Python's math module provides us with a series of mathematical functions that can help us perform operations such as exponentials, logarithms, square roots, and trigonometric functions.
When we find the square root, sum of squares, or exponentiation of a number, we often use the math module.
Take the logarithm operation: math.log(x[,base]) . This method will return the logarithm of x with the base as the base. If the base is omitted, it will use 2 as the base.
For example:
importmatha=math.log(144,12)b=math.log(36,6)print(a)print(b)
The output is:
2.02.0
Taking the square root operation: math.sqrt(x) , returns the square root of x.
For example:
importmatha=math.sqrt(16)b=math.sqrt(256)print(a)print(b)
The output is:
4.016.0
Exponentiation operation: pow(x,y) , returns x raised to the y power.
For example:
importmatha=math.pow(2,4)b=math.pow(10,3)print(a)print(b)
The output is:
16.01000.0
The use of trigonometric functions is similar to the above.
Trigonometric sine: math.sin(x)
Trigonometric cosine: math.cos(x)
Trigonometric tangent: math.tan(x)
Arcsine of radians: math.asin(x)
Arccosine of radians: math.acos(x)
Arctangent of radians: math.atan(x)
If you are converting radians to angles or angles to radians, use the following usage.
Radian rotation angle: math.degress(x)
Convert angle to radians: math.radinans(x)
Look at the following example:
importmatha=math.sin(30)b=math.cos(30)c=math.tan(30)d=math.asin(0.6)e=math.acos(0.6)f=math.atan(0.6)g= math.d egrees(2*math.pi)h=math.radians(360/math.pi)print(a)print(b)print(c)print(d)print(e)print(f)print(g)print( h)
The output is:
-0.98803162409286180.15425144988758405-6.4053311966462760.64350110879328440.92729521800161230.5404195002705842360.02.0
Note that we use math.pi to represent 'π' in Python.
The math module also provides several functions to help us perform rounding operations.
math.ceil(x): Returns the smallest integer greater than or equal to x.
math.floor(x): Returns the largest integer less than or equal to x.
At the same time, there is a built-in function round(x) in Python that provides us with rounding operations.
The code is as follows:
importmatha=math.ceil(3.5)b=math.floor(3.5)c=round(3.5)d=round(3.4)print(a)print(b)print(c)print(d)
The output is:
4343
This section mainly introduces the usage of the math module in Python. It should be noted that the functions in the math module only apply to integers and floating point numbers. If it is a complex number, we have to use the cmath module. I will not introduce it too much here. , the math module is a built-in module in the system, we can directly introduce and use it when designing mathematical operations.