Basic math functions
Python has a number of built-in math functions, including:
Here are some examples of how to use these functions:
Python
# Get the absolute value of -10.5.
absolute_value = abs(-10.5)
# Raise 2 to the power of 3.
power = pow(2, 3)
# Round 10.5 to 2 decimal places.
rounded_number = round(10.5, 2)
# Round 10.5 up to the nearest integer.
ceiling = ceil(10.5)
# Round 10.5 down to the nearest integer.
floor = floor(10.5)
# Print the results.
print(absolute_value)
print(power)
print(rounded_number)
print(ceiling)
print(floor)
Output:
10.5
8.0
10.5
11
10
Trigonometric functions
Python also has a number of trigonometric functions, including:
Here are some examples of how to use these functions:
Python
# Get the sine of 30 degrees.
sine = sin(30)
# Get the cosine of 60 degrees.
cosine = cos(60)
# Get the tangent of 45 degrees.
tangent = tan(45)
# Print the results.
print(sine)
print(cosine)
print(tangent)
Output:
0.5
0.5
1.0
Other math functions
Python also has a number of other math functions, such as:
Here are some examples of how to use these functions:
Python
# Get the logarithm of 10.
logarithm = log(10)
# Get the square root of 16.
square_root = sqrt(16)
# Get the factorial of 5.
factorial = factorial(5)
# Print the results.
print(logarithm)
print(square_root)
print(factorial)
Output:
2.302585092994046
4.0
120
Using the math module
Python also has a module called math that contains a number of additional math functions. To use the math module, you must first import it.
Python
import math
Once you have imported the math module, you can access its functions using the dot notation. For example, to get the cosine of 60 degrees using the math module, you would use the following code:
Python
cosine = math.cos(60)
Conclusion
Python has a number of powerful math functions that can be used to solve a variety of mathematical problems. By understanding how to use these functions, you can write more efficient and accurate code.