%Solves problem 6, p 60 of Turner
clc
clear all
close all
format long e
%Set the nujber of terms in the series approx 
%  to erf(x)
%x - value
x = linspace(0,4,200);
xsq=x.*x;
klim=9;  % corresponds to klim+1 terms
%initialize the series
sign = 1;  %corresponds to k=0
sum = 0;
term = x;  %term is also a vector
factk=1;  %fact accumulates the factorial
termk = 1;  %accumulates (2k+1)
%run the series
for k = 0:klim
    sum = sum + sign*term/(factk*termk); %vector of sums
    factk=factk*(k+1);
    sign = -sign;
    termk = termk + 2;
    term = term.*xsq;
end
approxerf = 2*sum/(sqrt(pi));  %vector of approximations
%fprintf('no of terms %3.0f  x= %5.3f \n ',klim+1,x)
%fprintf('approximate erf(x)= %12.9f \n',approxerf)
exacterf=erf(x);  %vector of exact erf values
%fprintf('Exact erf (x)=%12.9f Absolute Error= %12.9e\n',exacterf,abs(exacterf-approxerf))
%plot(x,approxerf,x,exacterf)
%figure
plot(x,approxerf-exacterf)
title(['Error in the ', num2str(klim+1), ...
        ' term approximation to the Erf(x)'])
xlabel('x')
ylabel('approx erf(x) - exact erf(x)')