riva February 2016

Taylor series approximation when the series is truncated after the first, second and third term, in MATLAB

I want to write an m-file function demoTaylorlog(x0,dx) that does the equivalent but for the Taylor series representation of f(x) = ln(x). This is what I have, but it does not work. I am not sure if it is the right code. How should I fix it?

function demoTaylorlog(x0,dx)

% demoTaylor  Taylor Series approximations for f(x) = 1/(1-x)
%Synopsis: 
%      demoTaylorlog(x0,dx)  
% Input:  x0 = (optional) point about which the Taylor Series expansion is 
%              made.  Default:  x0 = 1.6; 
%         dx = (optional) size of neighborhood over which the expansion 
%              is evaluated.  Default:  dx = 0.8 
%  Output:  a plot of f(x) and its Taylor Series approximations

if nargin<2,  x0 = 1.6;  dx = 0.8;  end

x = linspace(x0-dx/2,x0+dx/2,20);   
%  x-values at which f(x) is evaluated       
f(x)= log(x);                      
%  Exact f(x); notice the array operator
h = x - x0;                      
%  Avoid recomputing intermediate values, 
t = 1/(1-x0);                      
%    h and t p1x = t*ones(size(x)) + h*t^2;   
%  First order Taylor polynomial p2x = p1x+ (h.^2)*t^3;          
%  Second order "  "  " p3x = p2x + (h.^3)*t^4;          
%  Third
plot(x,fx,'-',x,p1x,'o-',x,p2x,'^-',x,p3x,'s-');
legend('exact','P_1(x)','P_2(x)','P_3(x)',4);
xlabel('x');    
ylabel('Approximations to f(x) = 1/(1-x)');

end

Answers


dubafek February 2016

In the statement f(x)= log(x); f is a vector and log is a function. Suppose that your x vector is [0.12 0.24 0.36] then the statement with the error is equivalent to:

f(0.12) = log(0.12);
f(0.24) = log(0.24);
f(0.36) = log(0.36);

But if fis a vector the assignment to f(0.12) has no sense because .12 is not a positive integer or a logical value (as the error says).

You should write f = log(x);

Post Status

Asked in February 2016
Viewed 1,017 times
Voted 12
Answered 1 times

Search




Leave an answer