numpy-exercises
ipynb7 kBPython · 11 cellsIn TP 1: NumPy exercises
Lab - NumPy Arrays and Matplotlib
Exercise 1.1
Create an array of integers from to included. Convert it to float32, then reshape it to a matrix (discard or adapt one element if needed). Verify dtype, shape and size.
import numpy as np
def printTest(x, message):
print(message)
print("Number of dimensions:", x.ndim)
print(x, "\n")
# Initial Array
x = np.array([-3, -2, -1, 1, 2, 3], np.int32)
printTest(x, "Initial array")
# to float64
x = np.array(x.astype(np.float64))
printTest(x, "After type change")
x = np.array(x.reshape(2, 3))
printTest(x, "After dimension change")Exercise 1.3
Create a array with np.arange. Slice the central
block into C, set all entries of C to 999, and inspect the original array. Then force a
copy with C = C.copy() and repeat. What changes?
import numpy as np
x = np.arange(16).reshape(4, 4)
print("Original array:\n", x)
C = x[1:3, 1:3]
C[:] = 999
print("\nAfter modifying C (view):\n", x)Exercise 2.1
Generate a random matrix of integers in the range .
- Compute the mean of each row
- Compute the standard deviation of each column
- Calculate the global mean and standard deviation
- Normalize the matrix using the formula:
- Verify that the normalized matrix has mean close to 0 and standard deviation close to 1
import numpy as np
x = np.random.randint(-50, 50, size=(5, 5))
print("Original Matrix:\n", x)
for i in range(0, 5):
print(f"Row {i} mean: {x.mean(axis=1)}")
for i in range(0, 5):
print(f"Column {i} standard deviation: {x.std(axis=0)}")
globalMean = x.mean()
print(f"\nGlobal Mean: {globalMean}")
globalStd = x.std()
print(f"\nGlobal Standard Deviation: {globalStd}")
normalized = (x - globalMean) / globalStd
print(f"\nNormalized normal form: ", normalized)
testMean = normalized.mean()
print(f"\nNormalized mean: {testMean}")
testStandardDeviation = normalized.std()
print(f"\nNormalized standard deviation: {testStandardDeviation}")Exercise 3.1
Plot both and on the same axes from to . Use different line styles or colors, add a legend, and a grid.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2 * np.pi, 100)
sin_x = np.sin(x)
cos_x = np.cos(x)
plt.plot(x, sin_x, label="sin(x)", color="blue", linestyle="-")
plt.plot(x, cos_x, label="cos(x)", color="orange", linestyle="--")
plt.title("Plot of sin(x) and cos(x)")
plt.xlabel("x (radians)")
plt.ylabel("Function value")
plt.legend()
plt.grid(True)
plt.show()Exercise 3.3
Generate 300 random points with coordinates uniformly sampled in . Plot them with a scatter plot, then highlight in a different color the points inside the unit circle .
import numpy as np
import matplotlib.pyplot as plt
# Generate 300 random points in the range [-1, 1] for both x and y
num_points = 300
x = np.random.uniform(-1, 1, num_points)
y = np.random.uniform(-1, 1, num_points)
def f(x, y):
return x**2 + y**2
# Determine which points are inside the unit circle
inside_circle = x**2 + y**2 <= 1
# Create a scatter plot
plt.figure(figsize=(8, 8))
plt.scatter(x[inside_circle], y[inside_circle], color="blue", label="Inside Circle")
plt.scatter(x[~inside_circle], y[~inside_circle], color="red", label="Outside Circle")
# Draw the unit circle for reference
circle = plt.Circle(
(0, 0), 1, color="green", fill=False, linestyle="--", label="Unit Circle"
)
plt.gca().add_artist(circle)
plt.title("Scatter Plot of Random Points with Unit Circle Highlighted")
plt.xlabel("x")
plt.ylabel("y")
plt.axhline(0, color="black", linewidth=0.5, ls="--")
plt.axvline(0, color="black", linewidth=0.5, ls="--")
plt.gca().set_aspect("equal", adjustable="box")
plt.legend()
plt.grid(True)
plt.show()