feat: Newton Verfahren mit Schrittweitensteuerung
This commit is contained in:
parent
5f7f9c4097
commit
6ba240a1d5
70
src/optimierung/schrittweitensteuerung.py
Normal file
70
src/optimierung/schrittweitensteuerung.py
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
# %%
|
||||||
|
import numpy as np
|
||||||
|
import sympy as sp
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
|
||||||
|
# Parameter
|
||||||
|
N = 200
|
||||||
|
x = sp.Symbol("x")
|
||||||
|
|
||||||
|
# Funktion
|
||||||
|
f_sym = sp.sin(3*x) + 0.02 * x ** 2
|
||||||
|
#f_sym = x**4 - 10 * x**2 + x
|
||||||
|
#f_sym = -sp.cos(2 * sp.pi * x)
|
||||||
|
|
||||||
|
# Ableitungen
|
||||||
|
f = sp.lambdify(x, f_sym, "numpy")
|
||||||
|
f_prime = sp.lambdify(x, sp.diff(f_sym, x), "numpy")
|
||||||
|
f_second = sp.lambdify(x, sp.diff(f_sym, x, 2), "numpy")
|
||||||
|
|
||||||
|
# Daten
|
||||||
|
# x_data = np.linspace(-4, 4, N)
|
||||||
|
x_data = np.linspace(-4, 4, N)
|
||||||
|
f_data = f(x_data)
|
||||||
|
|
||||||
|
# Plot
|
||||||
|
plt.figure(1)
|
||||||
|
plt.plot(x_data, f_data)
|
||||||
|
plt.xlabel("x")
|
||||||
|
plt.ylabel("y")
|
||||||
|
plt.grid("on")
|
||||||
|
plt.show()
|
||||||
|
|
||||||
|
# Newton Verfahren
|
||||||
|
# Startwert
|
||||||
|
#startwerte = [0.01, 0.02, 0.05, 0.1, 0.2, 0.23, 0.24, 0.245, 0.248, 0.249, 0.2499]
|
||||||
|
#startwerte = [1.1]
|
||||||
|
startwerte = [6.6, 3.4, 8.38]
|
||||||
|
|
||||||
|
# Iterationsformel
|
||||||
|
x_n = lambda x, c: x - c*(f_prime(x) / np.abs(f_second(x)))
|
||||||
|
|
||||||
|
print(60 * "-")
|
||||||
|
# Iteration
|
||||||
|
for x_0 in startwerte:
|
||||||
|
n = 0
|
||||||
|
c = 1
|
||||||
|
x_i = x_0
|
||||||
|
f_x = f(x_0)
|
||||||
|
f_x_prime = f_prime(x_0)
|
||||||
|
f_x_second = f_second(x_0)
|
||||||
|
print(f"x_{n}: {x_0}\nc: {c}\nf(x_{n}): {f_x}\nf'(x_{n}): {f_x_prime}\nf''(x_{n}): {f_x_second}\n")
|
||||||
|
|
||||||
|
limit = 1000
|
||||||
|
|
||||||
|
while np.abs(f_x_prime) > 1e-10 and limit > 0:
|
||||||
|
x_i = x_n(x_i, c)
|
||||||
|
if c == 1:
|
||||||
|
n += 1
|
||||||
|
f_nm1 = f_x
|
||||||
|
f_x = f(x_i)
|
||||||
|
f_x_prime = f_prime(x_i)
|
||||||
|
f_x_second = f_second(x_i)
|
||||||
|
print(f"x_{n}: {x_i}\nc: {c}\nf(x_{n}): {f_x}\nf'(x_{n}): {f_x_prime}\nf''(x_{n}): {f_x_second}\n")
|
||||||
|
if f_x > f_nm1:
|
||||||
|
c *= 0.7
|
||||||
|
else:
|
||||||
|
c = 1
|
||||||
|
limit -= 1
|
||||||
|
print(60 * "-")
|
||||||
|
# %%
|
||||||
Loading…
x
Reference in New Issue
Block a user