Professional Documents
Culture Documents
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return x**2 + 10 * np.sin(x)
x = np.arange(-5, 5, 0.1)
plt.plot(x, f(x))
plt.show()
# And plot it
import matplotlib.pyplot as plt
plt.figure(figsize=(6, 4))
plt.scatter(x_data, y_data)
############################################################
# Now fit a simple sine function to the data
import scipy as sp
print(params)
############################################################
# And plot the resulting curve on the data
plt.figure(figsize=(6, 4))
plt.scatter(x_data, y_data, label="Data")
plt.plot(x_data, test_func(x_data, *params), label="Fitted function")
plt.legend(loc="best")
plt.show()
Άσκηση 3: Interpolation
# Generate data
import numpy as np
np.random.seed(0)
measured_time = np.linspace(0, 1, 10)
noise = 1e-1 * (np.random.random(10) * 2 - 1)
measures = np.sin(2 * np.pi * measured_time) + noise
plt.figure(figsize=(6, 4))
plt.plot(measured_time, measures, "o", ms=6, label="measures")
plt.plot(interpolation_time, linear_results, label="linear interp")
plt.plot(interpolation_time, cubic_results, label="cubic interp")
plt.legend()
plt.show()
def f(x):
return x**2 + 10 * np.sin(x)
############################################################
# Find minima
############################################################
import scipy as sp
# Global optimization
grid = (-10, 10, 0.1)
xmin_global = sp.optimize.brute(f, (grid,))
print(f"Global minima found {xmin_global}")
# Constrain optimization
xmin_local = sp.optimize.fminbound(f, 0, 10)
print(f"Local minimum found {xmin_local}")
############################################################
# Root finding
############################################################
############################################################
# Plot function, minima, and roots
############################################################