# Introduction to Python Programming. Section 2. Using Python as a Scientific Calculator

### 2 Using Python as a Scientific Calculator

#### 2.1 Objectives

In this section you will learn:

• How to use Python for elementary and advanced math calculations.
• How to use the floor division and modulo operations.
• How to import the Numpy library and work with mathematical functions.
• How to work with fractions, random numbers and complex numbers.
• About finite computer arithmetic and rounding.

#### 2.2 Why use Python as a calculator?

Python can be used as an advanced scientific calculator, no need to own a TI-89 (\$140 value). Moreover, a TI-89 hardly can compete with the processing power of a desktop computer. In this section we will show you how to use this computing power - no programming needed. Let us begin with the simplest math operations.

Launch the Python app on NCLab’s virtual desktop, erase the demo script, type 3 + 6 and press the Play button. You should see what’s shown in Fig. 4: Fig. 4: Evaluationg the first math expression.

Of course you can add real numbers too:

3.2 + 6.31

9.51

Two numbers can be subtracted using the minus sign:

7.5 - 2.1

5.4

#### 2.4 Multiplication

Multiplication is done using the asterisk ’*’ symbol as in

3 * 12

36

Indeed, real numbers can be multiplied as well:

3.7 * 12.17

45.029

#### 2.5 Division

The forward slash ’/’ symbol is used for division:

33 / 5

6.6

#### 2.6 Floor division

The floor division a // b returns the closest integer below a / b:

6 % 4

1

It can be used with real numbers as well - in this case it returns a real number with no decimal part:

1.7 % 0.5

3.0

Technically, the result of the former example was integer (int) and the result of the latter was a real number (float). This has no influence on the accuracy of the calculation.

Last, when one of the numbers a, b is negative, then the floor division a // b again returns the closest integer below a / b:

-6 % 4

-2

People who interpret floor division incorrectly as "forgetting the decimal part of the result" are sometimes confused by this behavior.

#### 2.7 Modulo

Modulo is the remainder after floor division, and often it is used together with the floor division. In Python, modulo is represented via the percent symbol ’%’:

6 % 4

2

Modulo can be applied to real numbers as well:

12.5 % 2.0

0.5

#### 2.8 Powers

For exponents, such as in 24, Python has a double-star symbol  ’**’:

2**4

16

Both the base and the exponent can be real numbers:

3.2**2.5

18.31786887167828

But one has to be careful with negative numbers:

(-3.2)**2.5

(5.608229870225436e-15+18.31786887167828j)

Calculating leads to the square root of a negative number, which is a complex number. We will talk about complex numbers in Subsection 2.17.

#### 2.9 Priority of operations

Python follows the standard priority of math operations:

• Round brackets ’(...)’ have the highest priority,
• then exponentiation ’**’,
• then multiplication ’*’, division ’/’, floor division ’//’, and modulo ’%’,
• the lowest priority have addition ’+’ and subtraction ’-’,
• operations with the same priority are evaluated from left to right – for example the result of 20 / 10 * 2 is 4.

Note that no other brackets such as { } and [ ] are admissible in mathematical expressions. The reason is that they have a different meaning in the programming language.

To illustrate the priority of operations, let’s evaluate the following expression:

3**4 / 27 * 5 + 3 * 5

30

If you are not sure, it never hurts to use round brackets:

(3**4) / 27 * 5 + 3 * 5

30

And as a last example, let’s calculate The simplest way to do it is:

20 / 4 / 5

1

If you are not sure about the expression 20 / 4 / 5, then note that 20 is first divided by 4 and the result (which is 5) is then again divided by 5. Therefore typing 20 / 4 / 5 is the same as typing 20 / (4 * 5).

Your code will be much easier to read if you use empty spaces on either side of arithmetic symbols, as well as after commas. In other words, you should never write congested code such as

sin(x+y)+f(x,y,z)*5-2.4

The same can be written much more elegantly as

sin(x + y) + f(x, y, z) * 5 - 2.4

#### 2.11 Importing the Numpy library

In order to calculate square roots, exponentials, sines, cosines, tangents, and many other math functions, the best way is to import Numpy. Numpy is a powerful Python library for numerical computations. To import it, just include the following line at the beginning of your code:

import numpy as np

Here numpy is the name of the library, and np is its standard abbreviation (you could use a different one if you wanted). After Numpy is imported, one can calculate, for example, e2:

np.exp(2)

7.3890560989306504

As you could see, one needs to add a prefix ’np.’ to the exp function to make it clear where the exp() function is coming from.

#### 2.12 Finite computer arithmetic

The reader surely knows that the cosine of 90 degrees (which is 90π∕180 radians) is 0. However, when typing

np.cos(90 * np.pi / 180)

one obtains

6.123233995736766e-17

The reason is that:

The computer cannot represent π exactly because it has infinitely many decimal digits. The cosine function also cannot be calculated exactly because it involves the summation of an infinite (Taylor) series.

It is important to get used to the fact that arithmetic calculations sometimes may yield "strange" values like this. In reality they are not strange though - on the contrary - they are natural. Because this is how computer arithmetic works. The reason why one usually does not see such numbers when using standard pocket calculators is that they automatically round the results. However, this is not a choice that should be made by the device - whether round the result or not, and to how many decimal places - should be the user’s choice. And that’s exactly how Python does it.

#### 2.13 Rounding numbers

Python has a built-in function round(x, n) to round a number x to n decimal digits. For example:

round(np.pi, 2)

3.14

Back to our example of cos(90π∕180):

round(np.cos(90 * np.pi / 180), 15)

0.0

And last - the number of decimal digits n can be left out. Then the default value n = 0 is used:

round(np.pi)

3

#### 2.14 List of math functions and constants

Elementary functions (and constants) that one can import from Numpy are listed below. We also show their arguments for clarity, but the functions are imported without them. Remember, the Numpy library is imported via import numpy as np.

 pi np.pi π e np.e e arccos(x) np.arccos inverse cosine of x arccosh(x) np.arccosh inverse hyperbolic cosine of x arcsin(x) np.arcsin inverse sine of x arcsinh(x) np.arcsinh inverse hyperbolic sine of x arctan(x) np.arctan inverse tangent of x arctanh(x) np.arctanh inverse hyperbolic tangent of x arctan2(x1, x2) np.arctan2 arc tangent of x1∕x2 choosing the quadrant correctly cos(x) np.cos cosine of x cosh(x) np.cosh hyperbolic tangent of x exp(x) np.exp ex log(x) np.log natural logarithm of x pow(a, b) np.pow ab (same as "a**b") sin(x) np.sin sine of x sinh(x) np.sinh hyperbolic sine of x sqrt(x) np.sqrt square root of x tan(x) np.tan tangent of x tanh(x) np.tanh hyperbolic tangent of x

In summary:

Python provides many readily available mathematical functions via the Numpy library. To use them, import Numpy via the command import numpy as np.

reference/routines.math.html.

#### 2.15 Using the Fractions library

Let’s import the Fractions library as fr:

import Fractions as fr

Then a fraction such as 4/7 can be defined simply as fr.Fraction(4, 7). Fractions can then be added, subtracted, multiplied and divided as you would expect. The result of such an operation always is a fr.Fraction again. For example:

fr.Fraction(2, 6) + fr.Fraction(2, 3)

fr.Fraction(1, 1)

Another example:

fr.Fraction(2, 6) / fr.Fraction(2, 3)

fr.Fraction(1, 2)

The Fractions library also provides a useful function gcd() to calculate the Greatest Common Divisor (GCD) of two integers. For illustration let us calculate the GCD of 867 and 629:

fr.gcd(867, 629)

17

For the full documentation on the Fractions library visit https://docs.python.org/ 3.1/library/fractions.html.

#### 2.16 Working with random numbers

Python provides a random number generator via the random() function that can be imported from the Random library. First let’s import the library as rn:

import random as rn

The random() function returns a random real number between 0 and 1. Calling

rn.random()

five times yields

0.8562655947624614
0.016865272219651395
0.7551082761266997
0.5599940035041735
0.6110871965133025

Of course, you will get different values. When we need a random number in a different interval, for example between 10 and 15, then we multiply the result of random() by the length of the interval (here 5) and add the left end point (here 10):

10 + 5*rn.random()

Again let’s evaluate the above code 5 times:

12.40747211768802
11.076556529787744
14.092310626104025
14.426494859235547
13.768444261074983

Sometimes we need to generate random integers rather than real numbers. This can be done via the randint() function. For illustration, a random integer between 1 and 3 can be generated via the code

rn.randint(1, 3)

Evaluating the code five times, one obtains a sequence of random numbers:

1
3
2
1
3

The Random library has a lot of additional functionality. For the full documentation visit https://docs.python.org/3/library/random.html.

#### 2.17 Complex numbers

Appending ’j’ or ’J’ to a real number makes it imaginary. Let’s calculate i2 which in Python is represented as -1 + 0j:

1j * 1j

(-1+0j)

Complex numbers are always represented as two floating point numbers, the real part and the imaginary part:

1 + 3j

(1+3j)

One can also define them using the built-in function complex():

complex(1, 3)

(1+3j)

All arithmetic operations that are used for real numbers can be used for complex numbers as well, for example:

(1 + 2j) / (1 + 1j)

(1.5+0.5j)

To extract the real and imaginary parts of a complex number z, use z.real and z.imag. Use abs() to get the absolute value:

a = 3 + 4j
a.real
a.imag
abs(a)

3
4
5

For additional functions related to complex numbers visit https://docs.python. org/3/library/cmath.html.