Forelesning 5: Likninger og nullpunkter#
Uledninger og forklaringer på tavla (se også videoer på nettsidene).
Halveringsmetoden#
def f(x):
return 2*x - 2
a = -5
b = 12
c = (a+b)/2
tol = 1E-12
while f(c) != 0:
if f(a)*f(c) < 0:
b = c
elif f(b)*f(c) < 0:
a = c
c = (a+b)/2
print(c)
1.0
def f(x):
return 2*x - 2
a = -5
b = 12
c = (a+b)/2
i = 0
tol = 1E-12
while abs(f(c)) > tol:
if f(a)*f(c) < 0:
b = c
elif f(b)*f(c) < 0:
a = c
c = (a+b)/2
i += 1
print(c, i)
1.000000000000341 42
def halveringsmetoden(f, a, b, tol = 1E-12):
c = (a + b)/2
i = 0
while abs(f(c)) > tol:
if f(a)*f(c) < 0:
b = c
elif f(b)*f(c) < 0:
a = c
c = (a + b)/2
i += 1
return c, i
nullpunkt, iterasjoner = halveringsmetoden(f, -5, 12)
print(f"Nullpunktet er i x = {nullpunkt}. Nullpunktet ble funnet etter {iterasjoner} iterasjoner.")
Nullpunktet er i x = 1.000000000000341. Nullpunktet ble funnet etter 42 iterasjoner.
Newtons metode#
def f(x):
return 2*x**3 - 5
def fder(x):
return 6*x**2
x = 10
for i in range(10):
x = x - f(x)/fder(x)
print(x)
1.3572088082974534
import matplotlib.pyplot as plt
import numpy as np
xverdier = np.linspace(0,2,10000)
yverdier = f(xverdier)
plt.plot(xverdier, yverdier)
plt.grid()
def newtons_metode(f, fder, x, tol = 1E-12):
teller = 0
while abs(f(x)) > tol:
x = x - f(x)/fder(x)
teller += 1
return x, teller
nullpunkt, teller = newtons_metode(f, fder, 5)
print(f"Nullpunktet: {nullpunkt}, Antall iterasjoner: {teller}")
Nullpunktet: 1.3572088082974532, Antall iterasjoner: 8