To begin with: what are these “built-in” math functions that everyone keeps talking about? Basically, they’re just fancy ways for Python to do basic arithmetic without you having to type out every single operation yourself. For example, instead of writing `2 + 3`, you can use the built-in function `add(2, 3)` (just kidding, that doesn’t exist).
But seriously, let’s take a look at some of these functions and what they do:
1. `math.sqrt()` This one is pretty straightforward: it calculates the square root of whatever number you give it. For example, if you call `math.sqrt(25)`, Python will return 5 (because 5 times itself equals 25).
2. `math.pow()` If you’re feeling fancy and want to raise a number to an exponent, this is the function for you! Just pass in two arguments: the base number and the exponent. For example, if you call `math.pow(2, 3)`, Python will return 8 (because 2 raised to the power of 3 equals 8).
3. `math.floor()` This function rounds a given number down to the nearest integer. So if you call `math.floor(5.7)`, Python will return 5.
4. `math.ceil()` On the other hand, this function rounds a given number up to the nearest integer. For example, calling `math.ceil(5.2)` would result in 6.
5. `math.round()` If you’re feeling indecisive and want to round a number to the nearest whole number (i.e., no decimals), this is your guy/gal! For example, calling `math.round(5.4)` would result in 5.
6. `math.sin()`, `cos()`, and `tan()` These functions are for all you trigonometry nerds out there (or anyone who needs to calculate sine, cosine, or tangent). Just pass in the angle as a radian value (in degrees, divide by 180 and multiply by pi) and Python will do the rest.
7. `math.log()` This function calculates the natural logarithm of a given number. For example, calling `math.log(27)` would result in approximately 3.979 (because the natural logarithm of 27 is around 4).
8. `math.exp()` If you’re feeling fancy and want to calculate e raised to a given power, this function has got your back! For example, calling `math.exp(1)` would result in approximately 2.718 (because e raised to the power of 1 is around 2.7).
9. `math.pi` This one’s pretty self-explanatory: it gives you the value of pi! For example, calling `math.pi` would return a float with approximately 31 decimal places (because pi is an irrational number that goes on forever and ever…).
There are many more out there, but these should get you started on your journey to becoming a true mathematical wizard in the world of programming.
Python’s built-in math functions
in python