Problem including tolerance and finding value of a certain term

17 views (last 30 days)
Joe on 6 Aug 2013
Currently doing revision for a MATLAB module next year. Was attempting a question and was hoping for some help it.
I am asked to consider this Taylor series expansion:
S(x,n)=(x-1) - 1/2(x-1)^2 + 1/3(x-1)^3 - 1/4(x-1)^4 +...+ ((-1)^(n-1))*(1/n)*(x-1)^n
From this write a matlab function that, given the values of x and a tolerance e, returns the value of k such that the absolute value of the k-th term of the taylor series expansion is less or equal than e.
The issue is with the script i have made:
function S = taylor()
clear all
clc
tol=1e-5 x = input('Select value of x = '); S = 0; m = input('Select value of n = ');
for n = 1:m S = S + ((-1) ^ (n-1)) .* (((x - 1) .^ n)./n); end
disp(' ') fprintf('S(x,n) = %8.4f\n' ,S)
end
As I am a beginner to MATLAB I have no idea how to include a tolerance in the calculation. I am also wondering how I can find the kth term of the series with an absolute value of less or equal e(tolerance).
Just to inform you I the value of e is 10e-5

Evan on 6 Aug 2013
Edited: Evan on 6 Aug 2013
If you're checking for a certain tolerance, you can, after each iteration, see if the value of your most recently calculated term is less than the tolerance value. However, since you don't know when this will occur, a FOR loop probably isn't your best bet. After all, what happens if you don't reach the tolerance in the number of iterations you've set?
So, a better strategy here would be a WHILE loop. You set a certain condition: until your most recent term is less than or equal to tol, you continue to iterate. Since you still need your n values to increment for each iteration, you just set n to your starting index (e.g. 1) at the beginning and perform n = n + 1 at the end of each iteration.
tol = 1e-5;
x = input('Select value of x = ');
S = 0;
n = 1;
while Si > tol
Si = ((-1) ^ (n-1)) .* (((x - 1) .^ n)./n);
S = S + Si;
n = n + 1;
end
disp(' ') fprintf('S(x,n) = %8.4f\n; n = %i' ,S,n-1)

Iain on 6 Aug 2013
tol = 0.001;
x = 5;
n = -1;
current_term = inf;
while abs(current_term) > tol
n = n + 1;
current_term = ((-1) ^ (n-1)) .* (((x - 1) .^ n)./n);
end
disp(['The answer is the ' num2str(n) 'th term'])

Categories

Find more on Interpolation in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by