Skip to content
Snippets Groups Projects
Commit 7e96592d authored by Roman Jan Ernst's avatar Roman Jan Ernst
Browse files

Prüfungsvorbereitung 3

parent c7c2ef9e
Branches
Tags 0.3.17
No related merge requests found
......@@ -311,7 +311,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.10"
"version": "3.12.8"
}
},
"nbformat": 4,
......
......@@ -262,7 +262,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.7"
"version": "3.12.8"
}
},
"nbformat": 4,
......
%% Cell type:markdown id:472674d0 tags:
# Übung 8: Numpy I
## Einführung in Numpy
%% Cell type:markdown id:39c985b1 tags:
## 1.1 Numpy Arrays
%% Cell type:markdown id:01aba513 tags:
### 1.1.1 Create Numpy arrays
Create the following numpy arrays
**A** - A 3x3 array filled with zeros. <br>
**B** - A 3x2 array where all elements have the value 1. <br>
**C** - A 4x4 matrix filled with the value 9. <br>
**D** - A 3x3 identity matrix. <br>
**E** - An array containing the numbers from 1 to 50. <br>
**F** -An array from 0 to 2 in 50 even steps. <br>
**G** - An array that starts at 100 and decreases in steps from -1 to 1. <br>
**H** - A 3x3 matrix with equally distributed random numbers
**I** - A 4x4 array with normally distributed random numbers sigma = 2 mean =5
Use the script below to check your solution
%% Cell type:code id:a2646805 tags:
``` python
import numpy as np
A = np.zeros((3,3))
B = np.ones((3,2))
C = np.full((4,4), 9)
D = np.eye(3)
E = np.arange(1,51)
F = np.linspace(0,2,51)
G = np.arange(100,0,-1)
H = np.random.rand(3,3)
I = np.random.randn(4,4)
```
%% Cell type:markdown id:03fc7e51 tags:
Use this code to check if your arrays are correct
%% Cell type:code id:34c910e4 tags:
``` python
import numpy as np
# Check the arrays
def check_arrays():
correct = True
# Lösung
A_correct = np.zeros((3, 3))
B_correct = np.ones((3, 2))
C_correct = np.full((4, 4), 9)
D_correct = np.eye(3)
E_correct = np.arange(1, 51)
F_correct = np.linspace(0, 2, 51)
G_correct = np.arange(100, 0, -1)
# Check the arrays
if not np.array_equal(A, A_correct):
print("A is wrong")
correct = False
if not np.array_equal(B, B_correct):
print("B is wrong")
correct = False
if not np.array_equal(C, C_correct):
print("C is wrong")
correct = False
if not np.array_equal(D, D_correct):
print("D is wrong")
correct = False
if not np.array_equal(E, E_correct):
print("E is wrong")
correct = False
if not np.allclose(F, F_correct, atol=1e-9):
print("F is wrong")
correct = False
if not np.array_equal(G, G_correct):
print("G is wrong")
correct = False
if H.shape != (3, 3):
print("H has the wrong shape")
correct = False
if I.shape != (4, 4):
print("I has the wrong shape")
correct = False
if correct:
print("Al arrays are correct!")
else:
print("Some of the arrays still have errors!")
# Execute check
check_arrays()
```
%% Output
A is wrong
Some of the arrays still have errors!
Al arrays are correct!
%% Cell type:markdown id:e617c8a9 tags:
### 1.1.2 Matrix multiplication:
Create a matrix MA which is created by multiplying matrix D (unit matrix) by matrix A <br>
Create a matrix MB by multiplying the matrix B (3x2 matrix of ones) by the transposed matrix of itself
%% Cell type:code id:d3caefb6 tags:
``` python
MA = np.dot(D, H)
print(MA)
```
%% Output
[[0.93883534 0.02507742 0.90341158]
[0.35094824 0.25788158 0.88219623]
[0.12466092 0.63380527 0.92915316]]
%% Cell type:markdown id:d5a37328 tags:
Create a matrix B_scaled by multiplying the matrix B by the scalar 5
%% Cell type:code id:18d062d4 tags:
``` python
```
%% Cell type:markdown id:fed487d4 tags:
### 1.1.3 Calculation of determinant and eigenvalues:
Calculate the determinant of matrix C
%% Cell type:code id:5eddfe63 tags:
``` python
det_C = np.linalg.det(C)
print(det_C)
```
%% Output
0.0
%% Cell type:markdown id:c7c7d0a9 tags:
Calculate the eigenvalues of matrix I
%% Cell type:code id:b514726e tags:
``` python
eig_I = np.linalg.eig(I)
print(eig_I)
```
%% Output
EigResult(eigenvalues=array([ 2.09977488+0.96028186j, 2.09977488-0.96028186j,
-1.02823831+0.j , -1.70139983+0.j ]), eigenvectors=array([[ 0.02242646+0.10365196j, 0.02242646-0.10365196j,
-0.69599856+0.j , -0.36185063+0.j ],
[-0.3869284 +0.51393776j, -0.3869284 -0.51393776j,
0.11494521+0.j , -0.26668154+0.j ],
[-0.13316263-0.23569895j, -0.13316263+0.23569895j,
-0.70455261+0.j , -0.86781017+0.j ],
[-0.70825238+0.j , -0.70825238-0.j ,
-0.07732546+0.j , 0.21177959+0.j ]]))
%% Cell type:markdown id:a8822ed4 tags:
### 1.2 Task (Advanced): Aircraft navigation
An aircraft flies along a fixed route that is defined by several waypoints. Each waypoint is represented by a vector that indicates its position in 3D space. The speed of the aeroplane is also given as a vector indicating the direction and speed at each point along the route. The time required to get from one waypoint to the next is to be calculated.
#### Given data:
- Waypoints as vectors in 3D space in km. <br>
P1 `[0, 0, 4]`, <br>
P2 `[100, 100, 2]`, <br>
P3`[300, 250, 5]`, <br>
P4 `[500, 800, 15]` <br>
- Speeds in km/min <br>
v1, v2, v3 `[8, 12, 6]`
#### Goal:
Implement a function `path_planning` that provides the following outputs:
1. The time to get from P1 to P2 from P2 to P3 and from P3 to P4.
The times should be rounded to one decimal place and written in the form
``` The aircraft needs XY minutes to get from waypoint X to waypoint Y.```
- finally caluclatee and print the total flight time
#### Hint:
- The distance between two points can be calculated using the norm of the difference vector. `np.linalg.norm` (with the parameter (endvector - startvector)).
- The time required to cover this distance at a given speed is calculated by dividing the distance by the speed standard.
%% Cell type:code id:061287c5 tags:
``` python
def path_planning(positions, speeds):
times=[]
for i in range(len(positions)-1):
distance = np.linalg.norm(positions[i+1]-positions[i])
time = distance / speeds[i]
times.append(time)
return times
positions1 = np.array([
[0,0,4],
[100,100,2],
[300,250,5],
[500,800,15]
])
speeds1 = np.array([8,12,6])
times = path_planning(positions1, speeds1)
total_time = np.sum(times)
ergebnisse = []
for i in range(len(times)):
print("das Flugzeug benötigt", np.round(times[i],2), "Minuten, von Punkt",i+1, "nach" ,i+2)
print(f" Insegsamt benötigt das Flugzeug {np.round(total_time,2)} Minuten für die Fahrt.")
```
%% Output
[17.679437208237143, 20.83483327933722, 97.55340417774597]
das Flugzeug benötigt 17.68 Minuten, von Punkt 1 nach 2
das Flugzeug benötigt 20.83 Minuten, von Punkt 2 nach 3
das Flugzeug benötigt 97.55 Minuten, von Punkt 3 nach 4
Insegsamt benötigt das Flugzeug 136.07 Minuten für die Fahrt.
%% Cell type:markdown id:f5a3a32a tags:
## 1.3 Task: Temperature data analysis
A time series of temperature data from our AvaNode is given, comprising hourly measurements over several days. Each measurement is stored in a 1D NumPy array.
### Goal:
Develop a function `analyze_temperatures` that calculates the statistical values for a given series of temperature data. The function should determine and return the following values:
- **Mean value** der Temperaturen.
- **Median** der Temperaturen.
- **Standard deviation** der Temperaturen.
- **Maximum** der Temperaturen.
- **Minimum** der Temperaturen.
### Given data:
- Temperature data as 1D NumPy array:
```python
temperatures = np.array([19.2, 21.4, 24.8, 23.5, 22.0, 20.8, 24.1, 22.0, 21.0, 20.5])
**Required result**:
Where necessary, round the result to two decimal places using the `numpy.round` rounding function <br>
mean': 21.93, 'median': 21.7, 'standard deviation': 1.65, 'maximum': 24.8, 'minimum': 19.2
%% Cell type:code id:347ffb59 tags:
``` python
```
%% Cell type:markdown id:1b8d6083 tags:
### Task: Calculating the mechanical work of a motor
#### Background
A motor generates mechanical work that varies as a function of time. The generated work \( W \) is calculated by the integral of the power \( P(t) \) over a certain period of time \( T \). The power of the motor can be measured as discrete values in a specific time interval.
#### Aufgabe
Implement the function `calculate_mechanical_work(P, T)`, which calculates the mechanical work \( W \) using the trapezoidal integration method of `scipy.integrate.trapz` and returns it as a float. <br>
**Hint:** The trapezoidal rule calculates the area under a curve by summing the area of a series of trapezoids drawn between two adjacent points on the graph of the function. This usually provides a more accurate approximation of the integral than the simple rectangular method.
![trapint](https://www.mathelounge.de/?qa=blob&qa_blobid=17953428120461981830) <br>
the integrator can be imported using ```from scipy.integrate import trapz ```<br>
trapz(y, x=None, dx=1.0, axis=-1) <br>
Parameters: <br>
- **`y`**: This is the array of function values that are to be integrated.
- **`x`** This is the array of x-values (most often time). If it is not specified, it is assumed that the x-values are evenly spaced. `dx`.
- **`dx`** (optional): This is the step distance between the x-values if `x` is not specified. By default, `dx=1.0`.
- **`axis`** (optional): The axis along which to integrate. By default, this is the last axis (`axis=-1`).
The following values are given:
- `P = [100, 150, 200, 250, 300]` the number of time steps can be summed with the power based on the length of the vector
- `T = 1` Time interval between measurements in seconds
**note:** the time steps t result can be optained from the length of the vector with the power values and the duration from the timesteps with the np.arange method
%% Cell type:code id:9f5a81b3 tags:
``` python
P = np.array([100, 150, 200, 250, 300]) # Performance at given points in time
T = 1 # Time interval
```
......
This diff is collapsed.
This diff is collapsed.
......@@ -587,7 +587,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.0"
"version": "3.12.8"
}
},
"nbformat": 4,
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment