3.1

Comp. Prob. 4 pg. 101

 

1. Write this function and save it in a file named “fun.m”

function y=fun(x)

y=6*(exp(x)-x)-6-3*x^2-2*x^3;

 

2. Write this function and save it in a file named “bisec.m”

function r=bisec(a,b,N)

for i=1:N

    c=(a+b)/2;

    [a b c fun(a) fun(b) fun(c)]

    if fun(a)*fun(c)<=0,

        b=c;

    else

        a=c;

    end

end

r=c;

 

3. From Matlab command line, type:

>> r=bisec(-1,1,10)

 

-----------------------------------------------------

3.2

Comp. Prob. 4 pg. 118

 

1. Write this function and save it in a file named “f1.m”

function y=f1(x)

y=2*x*(1-x^2+x)*log(x)-x^2+1;

 

2. Write this function and save it in a file named “f1p.m”

function yp=f1p(x)

yp=2-2*x^2+2*log(1-3*x^2+2*x);

 

3. Write this function and save it in a file named “newt.m”

function r=newt(x0,N)

x(1)=x0;

for i=2:N+1

    x(i)=x(i-1)-f1(x(i-1))/f1p(x(i-1));

    [x(i) f1(x(i))]

end

r=x(i);

 

4. From Matlab command line, type:

>> r=newt(.5,40) %from command line

 

 

-----------------------------------------------------

 

3.3

Comp. Prob. 8/132

 

1. Write this function and save it in a file named “f2.m”

function y=f2(x)

k=1; %Here we choose k=1, you could try different values

y=2*exp(-k)*x+1-3*exp(-k*x);

 

2. Write this function and save it in a file named “sec.m”

function r=sec(x0,x1,N)

x(1)=x0;

x(2)=x1;

for i=2:N

    sl=(x(i)-x(i-1))/(f2(x(i))-f2(x(i-1)));

    x(i+1)=x(i)-sl*f2(x(i));

    [x(i+1) f2(x(i))]

end

r=x(i);

 

3. From Matlab command line, type:

>> r=sec(0,1,10) %from command line

 

 

4.1

Comp. Prob. 9 Pg. 162

 

function p=lagrinterp(x,y)

n=length(x)-1;

sum=zeros(1,n-1);

for i=0:n

   a=1;

   z=[];

   for j=0:n

      if j~=i

         a=a/(x(i+1)-x(j+1));

         z=[z x(j+1)];

      end

   end

   l=poly(z)*a;

   sum=sum+l*y(i+1);

end

p=sum;

 

 

5.2

Comp. Prob. 1 Pg. 209

 

function T=trap(a,b,h)

T=0;

for x=a:h:b-h

   T=T+h/2*(f(x)+f(x+h));

end

 

 

function y=f(x);

y=x^2+cos(x);

 

 

8.2

Comp. Prob. 3(b) Pg. 392

 

function xx=RK4(a,b,h,x0)

xx=[];

x=x0;

for t=a:h:b

   K1=h*f2(t,x);

   K2=h*f2(t+.5*h,x+.5*K1);

   K3=h*f2(t+.5*h,x+.5*K2);

   K4=h*f2(t+h,x+K3);

   x=x+1/6*(K1+2*K2+2*K3+K4);

   xx=[xx x];

end  

 

 

function y=f2(t,x)

y=1/x^2-x*t;