Number of terms needed for Maclaurin series expansion (while loops)

4 visualizaciones (últimos 30 días)
Junkang Gao
Junkang Gao el 29 de En. de 2017
Comentada: Walter Roberson el 29 de En. de 2017
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 comentario
Walter Roberson
Walter Roberson el 29 de En. de 2017
+1 for taking the time to give your trial code and describing the difficulty you are observing.

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by