Let’s see how Python can do basic mathematics.
If you want to run this on Google Colab, click on the launch button on the top right of the electronic version of the book.
Addition, multiplication, exponentiation, division, etc.¶
Here are some examples.
1 + 2
1 + 2 + 3
1 + (2 + 3)
2 * 3
2 * (3 + 4)
That was easy… The only thing to remember here is that whatever you enclose in parentheses is evaluated first. Just like regular mathematics.
+ and the multiplication
* are called binary operators.
Let’s continue see some more binary operators. Just like before, try to guess the result before you run the code.
2 ** 3
5 ** 2
(1 + 2) ** 2
So, the binary operator
** exponentiates. Remember this. It is different than Matlab.
Here is another binary operator:
2 / 3
1 / 2
5 / (2 + 3) ** 2
Okay, let’s now divide with zero:
1 / 0
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-12-bc757c3fda29> in <module> ----> 1 1 / 0 ZeroDivisionError: division by zero
Oops… This is how error messages look in Python. You need to get used to reading them. Look what it says:
ZeroDivisionErro. Well, it’s obvious what it means. Note also this
----> 1 1 / 0. The first number is the line number of the code block in which the error occured. Let’s put the error a little bit further into the code, to see if that changes:
# A comment line # Another comment line 1 / 0 # the error line (by the way, this is another way to write comments)
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-13-9c68dade0b49> in <module> 1 # A comment line 2 # Another comment line ----> 3 1 / 0 # the error line (by the way, this is another way to write comments) ZeroDivisionError: division by zero
Notice that the error now appears in the third line. Read the errors.
The binary operator
/ is the division operator. What if we wanted integer division? Then you need to use the
3 // 2
9 // 2
6 // 4
Integer division by zero?
1 // 0
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-17-7fc8a4784866> in <module> ----> 1 1 // 0 ZeroDivisionError: integer division or modulo by zero
What about the remainder of the division. This is the so-called modulo operator
Guess the result of the following:
3 % 2
9 % 2
6 % 4
6 % 2
Let’s divide by zero again:
10 % 0
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-22-b4eaad6685bc> in <module> ----> 1 10 % 0 ZeroDivisionError: integer division or modulo by zero
What about negative numbers? Sure:
-4 + 5
-5 + 5
In the code block provided below evaluate the dot product of the vectors:
Remember that the dot product of two vectors is:
# Your code here (by the way, this is how Python comments look like!)
You can use scientific notation to define numbers in Python. For example:
Very often we want to round numbers. Here is how:
round work? You can use the
help to figure it out:
Help on built-in function round in module builtins: round(number, ndigits=None) Round a number to a given precision in decimal digits. The return value is an integer if ndigits is omitted or None. Otherwise the return value has the same type as the number. ndigits may be negative.
round() is our first example of a Python function. As a matter of fact, it is a built-in Python function. We will learn quite a few of them (but not all) during these hands-on activities. By the way
help() is another Python function.
Standard mathematical functions¶
Python has some built in functions.
They are organized in a python module called
Here is how you can import the functionality of the
You just do:
Now you can use
Here is how:
math.sin(math.pi / 2)
math.cos(math.pi / 3)
math.cos(math.pi / 3) ** 2 + math.sin(math.pi / 3) ** 2
math.sqrt(2) ** 2
Note that some of the results are not coming out exactly right. There is a bit of error. This are called floating point errors or numerical errors. Get used to them…
math.tan(math.pi / 3)
math.sin(math.pi / 3) / math.cos(math.pi / 3)
We saw how we can get \(\pi\). How about \(e\)?
What about \(e^2\)? You should use the
math.exp function in this case:
1 / math.exp(-2.0)
What happes to \(e^x\) when \(x\) is too big?
--------------------------------------------------------------------------- OverflowError Traceback (most recent call last) <ipython-input-47-e0c11add5017> in <module> ----> 1 math.exp(1000) OverflowError: math range error
Oops… It doesn’t handle this very well… An
Anyway, if you want to learn more about what is in
math go here (or just Google “Python math”).
Alterantively, you could use the
Help on module math: NAME math MODULE REFERENCE https://docs.python.org/3.8/library/math The following documentation is automatically generated from the Python source files. It may be incomplete, incorrect or include features that are considered implementation detail and may vary between Python implementations. When in doubt, consult the module reference at the location listed above. DESCRIPTION This module provides access to the mathematical functions defined by the C standard. FUNCTIONS acos(x, /) Return the arc cosine (measured in radians) of x. acosh(x, /) Return the inverse hyperbolic cosine of x. asin(x, /) Return the arc sine (measured in radians) of x. asinh(x, /) Return the inverse hyperbolic sine of x. atan(x, /) Return the arc tangent (measured in radians) of x. atan2(y, x, /) Return the arc tangent (measured in radians) of y/x. Unlike atan(y/x), the signs of both x and y are considered. atanh(x, /) Return the inverse hyperbolic tangent of x. ceil(x, /) Return the ceiling of x as an Integral. This is the smallest integer >= x. comb(n, k, /) Number of ways to choose k items from n items without repetition and without order. Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates to zero when k > n. Also called the binomial coefficient because it is equivalent to the coefficient of k-th term in polynomial expansion of the expression (1 + x)**n. Raises TypeError if either of the arguments are not integers. Raises ValueError if either of the arguments are negative. 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. cos(x, /) Return the cosine of x (measured in radians). cosh(x, /) Return the hyperbolic cosine of x. degrees(x, /) Convert angle x from radians to degrees. dist(p, q, /) Return the Euclidean distance between two points p and q. The points should be specified as sequences (or iterables) of coordinates. Both inputs must have the same dimension. Roughly equivalent to: sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q))) erf(x, /) Error function at x. erfc(x, /) Complementary error function at x. exp(x, /) Return e raised to the power of x. expm1(x, /) Return exp(x)-1. This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x. fabs(x, /) Return the absolute value of the float x. factorial(x, /) Find x!. Raise a ValueError if x is negative or non-integral. floor(x, /) Return the floor of x as an Integral. This is the largest integer <= x. fmod(x, y, /) Return fmod(x, y), according to platform C. x % y may differ. frexp(x, /) Return the mantissa and exponent of x, as pair (m, e). m is a float and e is an int, such that x = m * 2.**e. If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0. fsum(seq, /) Return an accurate floating point sum of values in the iterable seq. Assumes IEEE-754 floating point arithmetic. gamma(x, /) Gamma function at x. gcd(x, y, /) greatest common divisor of x and y hypot(...) hypot(*coordinates) -> value Multidimensional Euclidean distance from the origin to a point. Roughly equivalent to: sqrt(sum(x**2 for x in coordinates)) For a two dimensional point (x, y), gives the hypotenuse using the Pythagorean theorem: sqrt(x*x + y*y). For example, the hypotenuse of a 3/4/5 right triangle is: >>> hypot(3.0, 4.0) 5.0 isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) Determine whether two floating point numbers are close in value. rel_tol maximum difference for being considered "close", relative to the magnitude of the input values abs_tol maximum difference for being considered "close", regardless of the magnitude of the input values Return True if a is close in value to b, and False otherwise. For the values to be considered close, the difference between them must be smaller than at least one of the tolerances. -inf, inf and NaN behave similarly to the IEEE 754 Standard. That is, NaN is not close to anything, even itself. inf and -inf are only close to themselves. isfinite(x, /) Return True if x is neither an infinity nor a NaN, and False otherwise. isinf(x, /) Return True if x is a positive or negative infinity, and False otherwise. isnan(x, /) Return True if x is a NaN (not a number), and False otherwise. isqrt(n, /) Return the integer part of the square root of the input. ldexp(x, i, /) Return x * (2**i). This is essentially the inverse of frexp(). lgamma(x, /) Natural logarithm of absolute value of Gamma function at x. log(...) log(x, [base=math.e]) Return the logarithm of x to the given base. If the base not specified, returns the natural logarithm (base e) of x. log10(x, /) Return the base 10 logarithm of x. log1p(x, /) Return the natural logarithm of 1+x (base e). The result is computed in a way which is accurate for x near zero. log2(x, /) Return the base 2 logarithm of x. modf(x, /) Return the fractional and integer parts of x. Both results carry the sign of x and are floats. perm(n, k=None, /) Number of ways to choose k items from n items without repetition and with order. Evaluates to n! / (n - k)! when k <= n and evaluates to zero when k > n. If k is not specified or is None, then k defaults to n and the function returns n!. Raises TypeError if either of the arguments are not integers. Raises ValueError if either of the arguments are negative. pow(x, y, /) Return x**y (x to the power of y). prod(iterable, /, *, start=1) Calculate the product of all the elements in the input iterable. The default start value for the product is 1. When the iterable is empty, return the start value. This function is intended specifically for use with numeric values and may reject non-numeric types. radians(x, /) Convert angle x from degrees to radians. remainder(x, y, /) Difference between x and the closest integer multiple of y. Return x - n*y where n*y is the closest integer multiple of y. In the case where x is exactly halfway between two multiples of y, the nearest even value of n is used. The result is always exact. sin(x, /) Return the sine of x (measured in radians). sinh(x, /) Return the hyperbolic sine of x. sqrt(x, /) Return the square root of x. tan(x, /) Return the tangent of x (measured in radians). tanh(x, /) Return the hyperbolic tangent of x. trunc(x, /) Truncates the Real x to the nearest Integral toward 0. Uses the __trunc__ magic method. DATA e = 2.718281828459045 inf = inf nan = nan pi = 3.141592653589793 tau = 6.283185307179586 FILE /Users/iliasbilionis/opt/anaconda3/lib/python3.8/lib-dynload/math.cpython-38-darwin.so
The interesting thing to notice in the help is at the very end.
There are several special numbers defined.
1 / math.inf
math.inf + math.inf
Can you guess what it is? Let’s try something that will break it:
math.inf - math.inf
nan? This is another number defined in
nan means “not a number”.
Here are some other examples of how you can get it.
math.inf / math.inf
Basically, if you see a
nan, there is something wrong with your code.
In the code block provided below to evaluate the magnitude of the vector:
# Your code here