Search code examples
octave

Plotting Taylor polynomial for sin(x) in GNU Octave


I'm attempting to plot the Taylor polynomial for sin(x) at a=0 with input of m degrees, in GNU Octave. sin(x) is plotted along with the estimation.

m = int8(input('Input integer m in [0,10]: '));
if m<0 || m>10
    disp('Thanks for playing');
    return;
  end
x = [-5:0.01:5];

y1 = sin(x);
for n=0:m
  y2 = ((-1).^n/factorial(2*n+1))*x.^(2*n+1);
  plot(y2);
  hold on;
  end
plot(y1,'linewidth',4)
ylim([-1.5,1.5]);

Above code prints the following image:

enter image description here

What is causing every estimation to have so few inflection points? I have tried setting xlim([-5,5]) but that did not fix my issue.


Solution

  • Currently you only evaluate each term without taking the summation.

    You need to initialize y2 and update the sum per iteration:

    y2 = 0  % initialize y2
    
    for n = 0:m
      y2 = (-1).^n/factorial(2*n+1) * x.^(2*n+1) + y2;  % add to previous y2
      plot(y2);
      hold on;
    end