2.10. Math Library Functions¶
Occaisionally while programming, we may need to do more complex mathematical work than the basic math operators allow for.
The Python math library has a wide assortment of functions and predefined variables we can use to do so.
For instance, say we want to figure out the radius of a circle with an area of 100 sq. inches.
The formula to calculate this is \(radius = \sqrt{\frac{area}{\pi}}\). The math library has
a math.sqrt(number)
function that will give us the square root of whatever value we give.
It also has a built in value for pi (\({\pi}\)) that can be accessed as math.pi
.
To make use of these, we need to first import math
to make the math library available to use
in our program. We then can access things like math.sqrt
and math.pi
.
An important detail to notice is that math.sqrt
returns an answer to us that we must do
something with. Just like the line of code x * 2
doesn’t do anything unless we store the result,
(something like y = x * 2
), writing math.sqrt(area / math.pi)
would do the math, but then
throw away the answer. We need to store the answer into a variable if we want to do anything
with it.
You do not need to worry about memorizing these, we will introduce them again in later chapters as needed. But here are some more examples of math library functions.
Name |
Input |
Description |
---|---|---|
math.ceil |
number |
Returns the smallest integer (whole number) that is greator than or equal to the number.
|
math.floor |
number |
Returns the largest integer (whole number) that is less than or equal to the number.
|
math.fabs |
number |
Returns the absolute value of the number. |
math.log |
number, base |
Returns \(\log_{number} base\). Example: |