0% found this document useful (0 votes)
43 views

Code For Finite Difference Method and Shooting Method

This document provides code to solve a boundary value problem using two different methods: finite difference method and shooting method. The boundary value problem is -y''(x)=x(1-x), 0<x<1, with boundary conditions y(0)=A, y(1)=B. The finite difference method solves the problem directly, while the shooting method uses a root-finding algorithm to determine the initial condition that satisfies the boundary conditions.

Uploaded by

JERRY Yuan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Code For Finite Difference Method and Shooting Method

This document provides code to solve a boundary value problem using two different methods: finite difference method and shooting method. The boundary value problem is -y''(x)=x(1-x), 0<x<1, with boundary conditions y(0)=A, y(1)=B. The finite difference method solves the problem directly, while the shooting method uses a root-finding algorithm to determine the initial condition that satisfies the boundary conditions.

Uploaded by

JERRY Yuan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Code for finite difference method and

shooting method​

1 % The code is to solve the BVP​


2 % -y''(x)=x(1-x), 0<x<1,​
3 % y(0)=A, y(1)=B,​
4 % by using finite difference method and​
5 % shooting method.​
6
7 n=50;​
8 A=0; B=0;​
9 h=1/(n+1);​
10 x=0:h:1;​
11
12 % Finite difference method​
13 f=x.*(1-x);​
14 f=f';​
15 M=diag(-ones(n-1,1),-1)+diag(2*ones(n,1),0)+diag(-ones(n-1,1),1);​
16 b=h^2*f(2:n+1);​
17 b(1)=b(1)+A;​
18 b(n)=b(n)+B;​
19 u=M\b;​
20 plot(x,[A; u; B],'b+')​
21 hold on​
22 xx=0:0.01:1;​
23 uex=xx.*(1-xx).*(1+xx-xx.^2)/12;​
24 plot(xx,uex,'r')​
25 hold off​
26
27
28 % Method 2: Shooting method​
29
30 A=0; B=0;​
31 %b=0.083;​
32 b0=0.1;​
33 f=@(x,y) [y(2); -x.*(1-x)];​
34 xspan=[0 1];​
35 [X,Y]=ode45(f,xspan,[A b0]);​
36 F0=Y(end,1)-B;​
37
38 b1=0.08;​
39 f=@(x,y) [y(2); -x.*(1-x)];​
40 xspan=[0 1];​
41 [X,Y]=ode45(f,xspan,[A b1]);​
42 F1=Y(end,1)-B;​
43
44 b2=b1-F1*(b1-b0)/(F1-F0);​
45 f=@(x,y) [y(2); -x.*(1-x)];​
46 xspan=[0 1];​
47 [X,Y]=ode45(f,xspan,[A b2]);​
48 F2=Y(end,1)-B;​
49
50
51
52 figure​
53 plot(X,Y(:,1),'b+')​
54 hold on​
55 xx=0:0.01:1;​
56 uex=xx.*(1-xx).*(1+xx-xx.^2)/12;​
57 plot(xx,uex,'r')​
58 hold off​

You might also like