Numerisk lösning av ekvationer
Contents
Rita en figur och bestäm startvärde
f = @(x)cos(x)-x;
x = linspace(-3,2);
plot(x,f(x));
grid on
Förbättra mha Newton's metod
f = @(x)cos(x)-x;
df = @(x)-sin(x)-1;
x0 = 0.75
x1 = x0 - f(x0)/df(x0)
x2 = x1 - f(x1)/df(x1)
x0 =
0.750000000000000
x1 =
0.739111138752579
x2 =
0.739085133364485
Göres i loop. När ska loopen avslutas ?
clc
format long
xk = 0.75;
disp([xk f(xk)])
for i= 1:10
x = xk;
xk = x - f(x)/df(x);
h = abs(x-xk);
if h < 0.5e-8
break;
end
disp([xk h f(xk)]);
end
0.750000000000000 -0.018311131126179
0.739111138752579 0.010888861247421 -0.000043523430164
0.739085133364485 0.000026005388094 -0.000000000249910
Rita nollstället med en liten ring
hold on
plot(xk,f(xk),'ko')
Koden i Labpm
clc
f=@(x)cos(x)-x; Df=@(x)-sin(x)-1;
x = 1;
kmax = 10; tol = 0.5e-8;
for k = 1:kmax
h = -f(x)/Df(x);
x = x + h;
disp([x h]);
if abs(h) < tol, break, end
end
0.750363867840244 -0.249636132159756
0.739112890911362 -0.011250976928882
0.739085133385284 -0.000027757526078
0.739085133215161 -0.000000000170123
Newtons metod konvergerar inte alltid.
x0 = -pi/2;
x1 = x0 - f(x0)/df(x0)
x2 = x1 - f(x1)/df(x1)
x1 =
-Inf
x2 =
NaN
Färdig programvara (fzero)
clf; clc
f = @(x)cos(x)-x;
x = linspace(-3,2);
plot(x,f(x));
grid on
x0 = 0.7;
xx = fzero(f,x0);
xx
xx =
0.739085133215161
Numerisk derivering (ex)
f = @(x)cos(x)-x;
df = @(x)-sin(x)-1;
exakt = df(1)
h=0.1;
framat = (f(1+h)-f(1))/h
bakat = (f(1)-f(1-h))/h
exakt =
-1.841470984807897
framat =
-1.867061844425626
bakat =
-1.813076624025246