Dette lille program finder alle maksima og minima i functionen "func" som selvfølgelig skal defineres efter behov.
Man kan også give den x og y som arrays fx fra excel hvis man vil det.
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import find_peaks
# Definer en funktion med 4 maxima og 4 minima
def func(x):
return np.sin(x) * np.cos(x / 2) * np.sin(3 * x)
# Definer intervallet og punkter
x = np.linspace(0, 10 * np.pi, 1000)
y = func(x)
# Beregn den afledte af funktionen ved hjælp af np.gradient
dy = np.gradient(y, x)
# Find alle maxima og minima
peaks, _ = find_peaks(y)
troughs, _ = find_peaks(-y)
# Plot funktionen
plt.plot(x, y, label='Funktion')
plt.plot(x, dy, label='Afledte', linestyle='--')
# Plot maxima
plt.plot(x[peaks], y[peaks], "x", label='Maxima')
# Plot minima
plt.plot(x[troughs], y[troughs], "o", label='Minima')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Funktion og dens afledte med maxima og minima')
plt.grid()
plt.show()
# Print maxima og minima
maxima = [(x[p], y[p]) for p in peaks[:4]]
minima = [(x[t], y[t]) for t in troughs[:4]]
print("Maxima:", maxima)
print("Minima:", minima)