Solving a problem with the Shooting Newton Method in Matlab
Afficher commentaires plus anciens
I tried to implement the Shooting method using Newton method to solve a differential equation, but the exact solution recommended by the professor does not coincide with the numerical solution.
Equation:
-y''+exp(-x)/2(y'^2+y^2)=exp(-x)/2*cos(x)+2sin(x)
BC:
2y(0)-y'(0)=0
y(pi)=exp(pi)
Exact solution:
y=exp(x)+sin(x)
The graphs should coincide, but they don't.
Can you help me?
For testing
>> [x,u]= NonLinearShootingNewtonExercise(20,1,0.0001);
>> y=exp(x)+sin(x);
>> plot(x,u,'r*',x,y,'k-')
My code is:
[x,u]= NonLinearShootingNewtonExercise(20,1,0.0001);
y=exp(x)+sin(x);
plot(x,u,'r*',x,y,'k-')
function [x,u] = NonLinearShootingNewtonExercise(N,sk,tol)
%Shooting method using Netwod method
%Equation:
%-y''+exp(-x)/2(y'^2+y^2)=exp(-x)/2*cos(x)+2sin(x)
%BC:
%2y(0)-y'(0)=0
%y(pi)=exp(pi)
%Exact solution:
%y=exp(x)+sin(x)
%Input
%N: number of discretization point
%s0: initial value of s
%tol: tollerance
% Output:
% x: Vector containing the points at which the solution is approximated
% u: Approximated solution
%For testing
% [x,u]= NonLinearShootingNewtonExercise(20,1,0.0001);
% y=exp(x)+sin(x);
% plot(x,u,'r*',x,y,'k-')
epi=exp(pi);
h=pi/N;
x=0:h:pi;
ds=1+tol;
while ds>=tol
[xx,uvUV]=ode23(@fun,x,[sk 2*sk 1 2]); %I have 4 initial values (u,v,U,V)
%uvUV is an array of 4 coloumns and N+1 rows
phik=uvUV(N+1,1)+uvUV(N+1,2)-epi;
dphik=uvUV(N+1,3)+uvUV(N+1,4); %derivate of phi
skp1=sk-phik/dphik;
ds=abs(skp1-sk);
sk=skp1;
end
u=uvUV(:,1);
end
function uvp= fun(x,uvUV)
uvp=[uvUV(2); (exp(-x)/2*(uvUV(2)^2+uvUV(1)^2))-(exp(-x)/2+cos(x)+2*sin(x));...
uvUV(4);(exp(-x)*uvUV(1)*uvUV(3))+(exp(-x)*uvUV(2)*uvUV(4))];
%u is the first component and v is the second component
end
1 commentaire
Francesca
le 26 Sep 2023
Déplacé(e) : John D'Errico
le 26 Sep 2023
Réponses (1)
sol = fsolve(@fun,23,optimset('TolFun',1e-12,'TolX',1e-12));
fun(sol)
[X,Y] = ode_solver(sol);
figure(1)
hold on
plot(X,Y(:,1))
plot(X,exp(X)+sin(X))
hold off
grid on
sol = fsolve(@fun,30,optimset('TolFun',1e-12,'TolX',1e-12));
fun(sol)
[X,Y] = ode_solver(sol);
figure(2)
hold on
plot(X,Y(:,1))
plot(X,exp(X)+sin(X))
hold off
grid on
function res = fun(p)
[X,Y] = ode_solver(p);
res = 2*Y(end,1)-Y(end,2);
end
function [X,Y] = ode_solver(p);
fun_ode = @(x,y)[y(2);-exp(-x)/2*cos(x)-2*sin(x)+exp(-x)/2*(y(2)^2+y(1)^2)];
y0 = [exp(pi);p];
tspan = [pi,0];
[X,Y] = ode15s(fun_ode,tspan,y0,odeset('RelTol',1e-12,'AbsTol',1e-12));
end
1 commentaire
Francesca
le 20 Sep 2023
Catégories
En savoir plus sur Numerical Integration and Differential Equations dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


