%% Solution Exam 1 (MATH246, Spring 2024)

clearvars; format short g

%% Problem 1(a)
% separable, constant solution y(t)=1

syms y(t)       % defines symbolic variable t and symbolic function y(t)
Dy = diff(y);   
ode =  Dy+t*(y-1)^2==0;
dsolve(ode)

% We get two solutions: one from separation (for y\ne 1), and the constant solution y(t)=1.

dsolve(ode,y(2)==-1)

% solution does not exist for t^2=5, solution exists for t\in (-\sqrt5,\sqrt5)

dsolve(ode,y(2)==1)

% solution exists for all t\in(-\infty,\infty)
%% Problem 1(b)
% ODE M(t,y)+N(t,y)y'=0 is exact: \partial_yM = -4 = \partial_t N
% Find H(t,y) with \partial_t H = M=-4y+16t and \partial_y H = N =2y-4t: we get H(t,y)=y^2-4ty+8t^2.

ode =  -4*y+16*t+(2*y-4*t)*Dy==0;
dsolve(ode,'Implicit',true)      % solution in implicit form
dsolve(ode)
dsolve(ode,y(0)==-1)

% solution exists for 4t^2<1, i.e., t\in (-\frac12,\frac12)
%% Problem 2(a)
% stationary points:
% 0 (neg to pos), hence unstable
% 1 (pos to neg), hence stable
% 3 (neg to pos), hence unstable
% y<0: negative
% 0<y<1: positive
% 1<y<3: negative
% y>3: positive
%% Problem 2(b)
% (i) for y(1)=2 we get y(t)\to 1 as t\to\infty , y(t)\to 3 as t\to-\infty, solution exists for all t\in(\infty,\infty)
% (ii) for y(1)=-1 we get y(t)\to -\infty as t\to t_* (solution does not exist for t\ge t_* since improper integral is finite)
% y(t)\to 0 as t\to-\infty, solution exists for t\in(-\infty,t_*)
%% Problem 3(a)
% y(t) denotes total amount of water in tank at time t, y(0) = 50
% volume of water in tank at time t is 10+t
% average concentration in tank is \frac{y(t)}{10+t}
% ODE y' = 6 -2\frac{y}{10+t}, initial condition y(0)=50
%% Problem 3(b)
% linear ODE y'+\frac{2}{10+t}y=15, a(t)=\frac2{10+t}, A(t)=2\ln(10+t), integrating factor e^{A(t)} = (10+t)^2

ode =  Dy==6-2*y/(10+t);
dsolve(ode)
dsolve(ode,y(0)==50)

%% Problem 4

f = @(t,y) y-t^2;
t0 = 1; y0 = -1; h = 1;
s1 = f(t0,y0)        
yE = y0 + h*s1         % Euler approximation
s2 = f(t0+h,yE)
y1 = y0 + h*(s1+s2)/2

%
%
%