Aggrawal Puja
Aggrawal Puja

Reputation: 47

Taylor Series of ln(x) in Matlab

I am trying to compute the taylor series of ln(x) for any value of x.

What I have so far is:

 clear
 clc
 n = input('Enter number of iiterations (n): ' );
 x = input('enter value of x (x): ');
 y = zeros(1,n);
 for i = 0:n
  y(i+1)=sum + (-1)^(n+1)*(x-1)^n/n;
end

But this code seems to be broken and I can't figure out why. Any suggestions on how to improve?

Upvotes: 0

Views: 3347

Answers (3)

Pouyan
Pouyan

Reputation: 373

I suggest using built-in function and hopefully there is one. taylor(f,var) approximates f with the Taylor series expansion of f up to the fifth order at the point var = 0.


Specify Expansion Point :

Find the Taylor series expansions at x = 1 for these functions. The default expansion point is 0. To specify a different expansion point, use 'ExpansionPoint':

syms x
taylor(log(x), x, 'ExpansionPoint', 1)
ans =
x - (x - 1)^2/2 + (x - 1)^3/3 - (x - 1)^4/4 + (x - 1)^5/5 - 1

Specify Truncation Order :

The default truncation order is 6.

syms x
f = log(x);
t6 = taylor(f, x);

Use 'Order' to control the truncation order. For example, approximate the same expression up to the orders 8.

syms x
taylor(log(x), x, 'ExpansionPoint', 1, 'Order', 8);

Upvotes: 1

NKN
NKN

Reputation: 6434

This is a one liner in addition to the for-loop answer provided by @farbiondriven

For 0<x<1 :

sumLn = @(x, n)(sum(((-1).^(0:n-1)).*((x-1).^(1:n))./(1:n)));
sumLn(0.5,10)

ans =

   -0.6931

>> log(0.5)

ans =

   -0.6931

For x>0.5 :

sumLn = @(x, n)(sum( ((x-1)/x).^(1:n) ./ (1:n) ));
sumLn(2,10)

ans =

    0.6931


log(2) =

    0.6931

Note: The variable x in this formula is bounded as mentioned in this link.

Upvotes: 2

farbiondriven
farbiondriven

Reputation: 2468

Try this:

clear
clc

n = input('Enter number of iterations (n): ' );
x = input('enter value of x with abs value < 1 (x): ');
y = zeros(1,n+1);

y(1)=0;

for i = 1:n
    y(i+1)= y(i) + ((-1)^(i+1)*(x-1)^i/i);
end


txt = sprintf('The output is: %f', y(n+1))

Upvotes: 1

Related Questions