For this tutorial, we are going to use two Python modules: math and numpy. To make our lives easier, we are going to call numpy np.
import math
import numpy as np
We can use the factorial function in the math module to find the factorial of 4.
math.factorial(4)
## 24
We can use the sqrt function in the math module to find the square root of 34.
math.sqrt(34)
## 5.830951894845301
We can use the fabs function in the math module to find the absolute value of -6.
math.fabs(-6)
## 6.0
Similar to R, we can find 9 random numbers from a normal distribution. The 0 indicates the mean, and the 1 indicates the standard deviation.
np.random.normal(0,1,9)
## array([-0.88993181, 0.78224488, 0.32642425, 1.07748021, -0.98384685,
## 1.11441505, 0.73813003, 0.53994728, 0.22197931])
When you run this code chunk, you will see an array. An array is the same thing as a vector, but we will learn more about vectors later.
Similar to R, we can use help() to find more information. Let’s write code chunks to use help() on the functions we just talked about.
help(math.factorial)
## Help on built-in function factorial in module math:
##
## factorial(...)
## factorial(x) -> Integral
##
## Find x!. Raise a ValueError if x is negative or non-integral.
help(math.sqrt)
## Help on built-in function sqrt in module math:
##
## sqrt(...)
## sqrt(x)
##
## Return the square root of x.
help(math.fabs)
## Help on built-in function fabs in module math:
##
## fabs(...)
## fabs(x)
##
## Return the absolute value of the float x.
help(np.random.normal)
## Help on built-in function normal:
##
## normal(...) method of numpy.random.mtrand.RandomState instance
## normal(loc=0.0, scale=1.0, size=None)
##
## Draw random samples from a normal (Gaussian) distribution.
##
## The probability density function of the normal distribution, first
## derived by De Moivre and 200 years later by both Gauss and Laplace
## independently [2]_, is often called the bell curve because of
## its characteristic shape (see the example below).
##
## The normal distributions occurs often in nature. For example, it
## describes the commonly occurring distribution of samples influenced
## by a large number of tiny, random disturbances, each with its own
## unique distribution [2]_.
##
## .. note::
## New code should use the ``normal`` method of a ``default_rng()``
## instance instead; please see the :ref:`random-quick-start`.
##
## Parameters
## ----------
## loc : float or array_like of floats
## Mean ("centre") of the distribution.
## scale : float or array_like of floats
## Standard deviation (spread or "width") of the distribution. Must be
## non-negative.
## size : int or tuple of ints, optional
## Output shape. If the given shape is, e.g., ``(m, n, k)``, then
## ``m * n * k`` samples are drawn. If size is ``None`` (default),
## a single value is returned if ``loc`` and ``scale`` are both scalars.
## Otherwise, ``np.broadcast(loc, scale).size`` samples are drawn.
##
## Returns
## -------
## out : ndarray or scalar
## Drawn samples from the parameterized normal distribution.
##
## See Also
## --------
## scipy.stats.norm : probability density function, distribution or
## cumulative density function, etc.
## Generator.normal: which should be used for new code.
##
## Notes
## -----
## The probability density for the Gaussian distribution is
##
## .. math:: p(x) = \frac{1}{\sqrt{ 2 \pi \sigma^2 }}
## e^{ - \frac{ (x - \mu)^2 } {2 \sigma^2} },
##
## where :math:`\mu` is the mean and :math:`\sigma` the standard
## deviation. The square of the standard deviation, :math:`\sigma^2`,
## is called the variance.
##
## The function has its peak at the mean, and its "spread" increases with
## the standard deviation (the function reaches 0.607 times its maximum at
## :math:`x + \sigma` and :math:`x - \sigma` [2]_). This implies that
## normal is more likely to return samples lying close to the mean, rather
## than those far away.
##
## References
## ----------
## .. [1] Wikipedia, "Normal distribution",
## https://en.wikipedia.org/wiki/Normal_distribution
## .. [2] P. R. Peebles Jr., "Central Limit Theorem" in "Probability,
## Random Variables and Random Signal Principles", 4th ed., 2001,
## pp. 51, 51, 125.
##
## Examples
## --------
## Draw samples from the distribution:
##
## >>> mu, sigma = 0, 0.1 # mean and standard deviation
## >>> s = np.random.normal(mu, sigma, 1000)
##
## Verify the mean and the variance:
##
## >>> abs(mu - np.mean(s))
## 0.0 # may vary
##
## >>> abs(sigma - np.std(s, ddof=1))
## 0.1 # may vary
##
## Display the histogram of the samples, along with
## the probability density function:
##
## >>> import matplotlib.pyplot as plt
## >>> count, bins, ignored = plt.hist(s, 30, density=True)
## >>> plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *
## ... np.exp( - (bins - mu)**2 / (2 * sigma**2) ),
## ... linewidth=2, color='r')
## >>> plt.show()
##
## Two-by-four array of samples from N(3, 6.25):
##
## >>> np.random.normal(3, 2.5, size=(2, 4))
## array([[-4.49401501, 4.00950034, -1.81814867, 7.29718677], # random
## [ 0.39924804, 4.68456316, 4.99394529, 4.84057254]]) # random
After running these code chunks, you can see what the function does and the arguments of that function.
Write a code chunk to find 14 factorial.
math.factorial(6)
## 720
Write a code chunk to find the square root of 45.
math.sqrt(45)
## 6.708203932499369
Write a code chunk to find the absolute value of 13.
math.fabs(13)
## 13.0
Write a code chunk to find 10 random numbers from a normal distribution with mean 0 and standard deviation 1.
np.random.normal(0, 1, 10)
## array([ 1.26505884, -0.60464951, -0.81876522, -2.56917742, 1.0945363 ,
## -0.8859218 , 1.91258964, -0.15711987, 0.84456939, -0.82210435])
Write a code chunk to see what the copysign function from the math module in Python does.
help(math.copysign)
## Help on built-in function copysign in module math:
##
## copysign(...)
## copysign(x, y)
##
## Return a float with the magnitude (absolute value) of x but the sign
## of y. On platforms that support signed zeros, copysign(1.0, -0.0)
## returns -1.0.
1.) Write a code chunk to find 14 factorial.
2.) Write a code chunk to find the square root of 50.
3.) Write a code chunk to find the absolute value of -20.
4.) Write a code chunk to find 5 random numbers from a normal distribution with mean 0 and standard deviation 1.
5.) Write a code chunk to see what the exp function from the math module in Python does.
help(math.exp)
## Help on built-in function exp in module math:
##
## exp(...)
## exp(x)
##
## Return e raised to the power of x.