On Day 13 of our coding journey, we learned about the built-in math functions that are available in most programming languages.
These functions provide a wide range of functionality and help in performing common tasks without having to write code from scratch. In Python, there are many built-in functions available, including math built-in functions. Math built-in functions perform mathematical operations and are often used in scientific and engineering applications.
In this post, we will focus on math built-in functions in Python. We will discuss the most commonly used math built-in functions and the math module in Python, which provides additional math functions. We will also explore how math functions can be used in practical applications to solve real-world problems. So, let's dive in and explore the world of math built-in functions in Python!
You can see math module documentation here:
https://docs.python.org/3/library/math.html
The math module in Python provides additional math functions beyond the built-in ones we've discussed so far. Here's how you can import the math module and use some of its functions:
import math
# Using math.pi to get the value of pi
print(math.pi) # Output: 3.141592653589793
# Using math.ceil() to round up a number to the nearest integer
print(math.ceil(4.2)) # Output: 5
# Using math.floor() to round down a number to the nearest integer
print(math.floor(4.8)) # Output: 4
# Using math.sin() to calculate the sine of an angle in radians
print(math.sin(math.pi/2)) # Output: 1.0
# Using math.cos() to calculate the cosine of an angle in radians
print(math.cos(math.pi)) # Output: -1.0
# Using math.radians() to convert degrees to radians
print(math.radians(180)) # Output: 3.141592653589793
# Using math.degrees() to convert radians to degrees
print(math.degrees(math.pi/2)) # Output: 90.0
Here are some examples of how to use math built-in functions in Python:
print(abs(-4.3)) # Output: 4.3print(abs(3+4j)) # Output: 5.0print(pow(2, 3)) # Output: 8print(pow(2, -3)) # Output: 0.125print(sqrt(16)) # Output: 4.0print(sqrt(3)) # Output: 1.7320508075688772print(round(3.14159, 2)) # Output: 3.14print(round(4.6)) # Output: 5print(max(2, 4, 1, 7, 5)) # Output: 7print(max([2, 4, 1, 7, 5])) # Output: 7print(min(2, 4, 1, 7, 5)) # Output: 1print(min([2, 4, 1, 7, 5])) # Output: 1print(sum([2, 4, 1, 7, 5])) # Output: 19