sqrt(25)--------------------------------------------------------------------------- NameError Traceback (most recent call last) /tmp/ipykernel_1328/3140457483.py in <cell line: 0>() ----> 1 sqrt(25) NameError: name 'sqrt' is not defined
A module is a single Python file containing reusable variables, functions or classes.
A package is a collection of related modules that provides tools for a particular type of work.
Instead of writing every numerical algorithm ourselves, we can use packages containing functions that are already implemented and tested.
Examples:
| Package | Main use |
|---|---|
| NumPy | Numerical arrays and computations |
| Matplotlib | Plotting and visualization |
| Pandas | Data analysis |
| SciPy | Scientific computing |
| Scikit-learn | Machine learning |
Suppose we want to calculate the square root of 25. Can Python already provide a function for this instead of us writing the algorithm ourselves?
--------------------------------------------------------------------------- NameError Traceback (most recent call last) /tmp/ipykernel_1328/3140457483.py in <cell line: 0>() ----> 1 sqrt(25) NameError: name 'sqrt' is not defined
The sqrt() function already exists inside the math module.
Before using a package, Python must know that we want to use it.
The general syntax is:
For scientific computing, NumPy is normally imported as
Here, np is simply a short alias for numpy.
Import NumPy using the standard alias np and check the installed NumPy version.
deprecated
The main object in NumPy is the ndarray, or N-dimensional array.
A Python list may contain general objects, but a NumPy array is optimized for storing and processing numerical data efficiently.
Create the vector
$ x = \[\begin{bmatrix} 2 & 4 & 6 & 8 & 10 \end{bmatrix}\]$
as a NumPy array.
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
1
4
9
Can NumPy also represent a matrix?
$ A = \[\begin{bmatrix} 1 & 2 & 3\\ 4 & 5 & 6\\ 7 & 8 & 9 \end{bmatrix}\]. $
Create:
Useful NumPy functions include:
np.zeros(shape) — creates an array filled with zeros,np.ones(shape) — creates an array filled with ones,np.arange(start, stop, step) — creates regularly spaced values using a step size,np.linspace(start, stop, number) — creates a specified number of equally spaced values.Generate the numbers
[ 0,2,4,6,8 ]
using arange().
array([ 1. , 2.11111111, 3.22222222, 4.33333333, 5.44444444,
6.55555556, 7.66666667, 8.77777778, 9.88888889, 11. ])
In arange(start, stop, step).
For a simulation from (t=0) to (t=10) seconds, generate exactly 11 equally spaced time points.
For the matrix
$ A = \[\begin{bmatrix} 10 & 20 & 30\\ 40 & 50 & 60 \end{bmatrix}\], $
find its shape, number of dimensions, total number of elements and data type.
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /tmp/ipykernel_1328/4048500941.py in <cell line: 0>() ----> 1 A.elements AttributeError: 'numpy.ndarray' object has no attribute 'elements'
shape — dimensions of the array,ndim — number of dimensions,size — total number of elements,dtype — data type of the elements.Using the matrix below:
int32, int64, float32, float64
NumPy uses zero-based indexing, like Python lists.
For a one-dimensional array:
is the first element.
For a two-dimensional array:
selects an element.
The symbol : means take all entries along that direction.
Therefore:
means: second row, all columns.
and
means: all rows, third column.
One of the biggest advantages of NumPy is that arithmetic can be performed on entire arrays directly.
This is called vectorization.
Instead of processing each element manually with a loop, NumPy applies the operation to the complete array.
Let
\(x = [1,2,3,4].\)
Find:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) /tmp/ipykernel_1328/1825985778.py in <cell line: 0>() ----> 1 [1,2,3,4]**2 TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
Compare A * B and A @ B for the matrices below.
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) /tmp/ipykernel_1328/2343860730.py in <cell line: 0>() ----> 1 A @B ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 2 is different from 3)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) /tmp/ipykernel_1328/3887616290.py in <cell line: 0>() ----> 1 A.T * B ValueError: operands could not be broadcast together with shapes (3,2) (2,3)
array(20., dtype=float32)
For NumPy arrays:
performs element-wise multiplication.
For matrices:
performs matrix multiplication.
These are different operations.
NumPy provides vectorized mathematical functions.
Some
np.sqrt(x) — square root,np.exp(x) — exponential,np.log(x) — natural logarithm,np.sin(x) — sine,np.cos(x) — cosine,np.abs(x) — absolute value.For
\(x=[1,4,9,16,25],\)
calculate the square root of every element using one command.
np.sum(x) — sum,np.mean(x) — arithmetic mean,np.median(x) — median,np.std(x) — standard deviation,np.min(x) — minimum,np.max(x) — maximum.(These are only some of the functions not all)
The temperatures measured during five experiments are
\([28.5,30.0,29.5,31.0,27.5].\)
Find the mean, minimum and maximum temperatures.
A vehicle travels with the following measured velocities in m/s:
\(v=[0,5,10,15,20,25].\)
Using NumPy:
create the velocity array,
convert every velocity from m/s to km/h using
$ v_{{km/h}}=3.6v_{{m/s}}, $
find the average velocity in km/h,
find the largest velocity in km/h.
Try the question first before running the solution.
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /tmp/ipykernel_840/4118434146.py in <cell line: 0>() ----> 1 np.v*3.6 /usr/local/lib/python3.13/dist-packages/numpy/__init__.py in __getattr__(attr) 412 return char.chararray 413 --> 414 raise AttributeError("module {!r} has no attribute " 415 "{!r}".format(__name__, attr)) 416 AttributeError: module 'numpy' has no attribute 'v'
Slicing means selecting a part of an array.
The general form is
From the array
\(A=[10,20,30,40,50,60,70],\)
extract the elements 20, 30, 40, 50.
Using the same array:
For a matrix,
can be used to select a block of entries.
Given
$ A= \[\begin{bmatrix} 1&2&3&4\\ 5&6&7&8\\ 9&10&11&12 \end{bmatrix}\], $
extract the first two rows and the middle two columns.
Create the numbers 1 to 12 and reshape them into a (3) matrix.
The function
changes the shape while preserving the elements.
Can the same 12 elements be arranged as a (4 x 3) matrix?
Convert the following matrix into a one-dimensional array.
A multidimensional array can be converted into a one-dimensional array using
Find the transpose of a (2 x 3) matrix and compare the shapes before and after transposition.
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) /tmp/ipykernel_840/4181211480.py in <cell line: 0>() ----> 1 A.flatten(0) TypeError: order must be str, not int
For
\(A=[10,20,30],\qquad B=[2,4,5],\)
find:
(array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]]),
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]]))
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) /tmp/ipykernel_840/2301120001.py in <cell line: 0>() ----> 1 A@B ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 3 is different from 4)
Calculate
\([1,2,3]\cdot[4,5,6].\)
For example, adding
\([10,20,30]\)
to every row of
\(\begin{bmatrix} 1&2&3\\ 4&5&6 \end{bmatrix}\)
does not require a loop.
Add the vector [10, 20, 30] to every row of the matrix.
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) /tmp/ipykernel_840/456880799.py in <cell line: 0>() ----> 1 [10,10] +10 TypeError: can only concatenate list (not "int") to list
Evaluate \(e^x\) for \(x=0,1,2\).
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) /tmp/ipykernel_840/383732492.py in <cell line: 0>() ----> 1 np.log(np.array([6,1,2]),10) TypeError: return arrays must be of ArrayType
Generate five equally spaced angles from \(0\) to \(\pi\) and calculate their sine and cosine.
Find the absolute values of
$ [-4,-2,3,-8]. $
For
$ A=[15,8,30,22,10], $
find:
Use np.cumsum() to calculate the cumulative sum.
For
$ A= \[\begin{bmatrix} 10&20&30\\ 40&50&60 \end{bmatrix}\], $
find:
For
$ A=[12,5,18,7,25,3], $
check which elements are greater than 10.
Combine
$ A=[1,2,3] $
and
$ B=[4,5,6]. $
Suppose the displacement of an oscillator is
\(x(t)=2\sin(t).\)
We want to evaluate this function at several time points.
Generate 9 equally spaced points between (0) and (2), and calculate
$ x(t)=2(t) $
without using a loop.
The temperatures measured at eight time instants are
$ T=[25.0,26.5,28.0,29.2,30.1,29.8,28.7,27.5]. $
Using NumPy:
A moving object’s position is measured at equally spaced times:
\(x=[0,1.2,2.8,4.9,7.5,10.6].\)
The time points are
\(t=[0,1,2,3,4,5].\)
Using NumPy:
t,Write a Python program that accepts a positive integer and finds:
Example
Input: 58327
Number of digits = 5
Sum of digits = 25
Largest digit = 8
Smallest digit = 2
Write a function
that accepts a list of integers and returns a new list containing only the prime numbers.
Example
Input:
[4, 7, 10, 13, 18, 23, 1]
Output:
[7, 13, 23]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) /tmp/ipykernel_1350/4267519414.py in <cell line: 0>() ----> 1 [10]%[1,2,33] TypeError: unsupported operand type(s) for %: 'list' and 'list'