Number of terms needed for Maclaurin series expansion (while loops)
4 views (last 30 days)
Show older comments

Given the above problem, I've attempted to code this different ways based on what I knew and from the methods I found on the Internet.
function [ numOfTerms ] = lnOfOnePlusX( x )
actual=log(1+x);
n=1;
index=1;
summation=0;
difference=0;
% Calculating first term
approx(index)=(((-1)^(n+1))/n)*(x^n);
% Calculating the subsequent terms
n=n+1;
index=index+1;
while difference>=0.001
approx(index)=(((-1)^(n+1))/n)*(x^n);
summation=summation+approx(index);
difference=abs((approx(index)-approx(index-1))/approx(index));
n=n+1;
index=index+1;
end
end
We've not discussed the use of index before in class but it was on another MATLAB Answers page that was trying to implement Taylor series for something else.
Here's another set of code that I tried and it still didn't work. This one gives me an infinite loop because the while condition is always met, it seems like. I just don't have the function part because it was easier to work with.
clear, clc
x=0.1;
actual=log(1+x);
approx=x;
n=1;
difference=abs((actual-approx)/actual);
threshold=1E-3;
while difference>=threshold
n=n+1;
approx=approx+(((-1)^(n+1))/n)*(x^n);
difference=abs((actual-approx)/actual);
end
With x=0.1, we are there's supposed to be 3 terms. x=0.2: 4 terms. x=0.5: 7 terms. x=0.9: 31 terms.
1 Comment
Walter Roberson
on 29 Jan 2017
+1 for taking the time to give your trial code and describing the difficulty you are observing.
Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements 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!