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 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 (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
.
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.
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 |