Libraries and mathematical functions

Libraries and mathematical functions#

(Click here for the German version of this page)

Importing a library#

Python has an enormous selection of libraries. Be it libraries to create graphical content or libraries for machine learning.

In the context of algorithms and data structures, mathematical libraries are of particular interest. With these libraries one can use functions to calculate square roots, logarithms and much more.

To be able to use those helpful functions, one first has to import the appropriate library. From a logical perspective, it works similar to importing libraries in C. There is a keyword followed by the name of the library. Afterwards, the library can be used.

In C:

#include <Library_name.h>

In Python the keyword import is used:

import Library_name

For calculation of square roots and logarithms, the library math needs to be imported.

Therefore, you need the following statement:

import math

Then you can use the math functions.

Functions of the math library#

After importing the math library, the corresponding functions can be accessed with the prefix math., meaning you want to access a function of that library.

The square root of 25 could be calculated as follows using the function math.sqrt():

x = math.sqrt(25)
print(x)
# --> 5

To calculate the base 10 logarithm of x, one can use the function math.log10():

x = math.log10(100)
print(x)
# --> 2

information regarding math functions, such as trigonometric functions, can be found in the official Python documentation.

Exercise#

Here is the equation for the density function of a normal distribution, also known as a “gaussian bell curve”. The goal is not to understand this formula. We chose this formula since you can test whether you have understood how to utilize mathematical operators and functions. The only goal is to rewrite the formula into Python code and calculate the result for the given values \(\mu =3\), \(\sigma = 5\) and \(x=4\).

\(f(x\:|\:\mu,\sigma^2)=\frac{1}{\sigma\sqrt{2\pi}}e^{-\frac{1}{2}(\frac{x-\mu}{\sigma})^2}\)

To make it easier, the formula was slightly rewritten by replacing all the Greek letters (except pi) with the variable names.

Those should be the variable names used in the code.

\(result=\frac{1}{sigma\cdot\sqrt{2\cdot\pi}}\cdot e^{-\frac{1}{2}\cdot(\frac{x-mu}{sigma})^2}\)

The value for \(\pi\) can be retrieved with math.pi. The value for \(e\) can be retrieved with math.e. Pay attention to parentheses.

Example:

result = (a + b + c
         + d + e)

Good luck and have fun!

# Here you can attempt to solve the problem...
# Simply replace the ... below with your code.
# The output should be the result of the formula.
# Do you perhaps need a library?

mu = 3
sigma = 5
x = 4
print(
    ...
)
Ellipsis