trying to do a series sum in matlabAsk Question

问题:

I want to calculate the sum of a series in MATLAB The assignment is on the last page question 3 on this webpage The series's sum should be pi but when I used MATLAB to prove that it just does not converge to pi

What am I doing wrong in my code?

function f = equation(n)
for i=1:n;
    f=4*sum(((-1)^i)/(2*i+1))
    if f >= pi
        break;
    else 
        continue;
    end
end
end

EDIT :

function f = equation(n)
i=0:n;
f=4*sum((-1).^i ./(2*i+1));
plot(f,'x')
end

It does not work to plot(f) , what am I doing wrong ?

回答1:


There are a few things you are doing wrong. First, you aren't keeping track of the running sum, you are just defining each term inside the loop. You should instead have something like

function total = equation(n)
  total = 0;
  for i = 1:n
    total = total + (-1)^i / (2 * i + 1);
    if total > pi
      break;
    end
  end
  total = 4 * total;
end

Second, you don't want the break statement there. If you plot the partial sums of this series, you can see that it oscillates either side of pi -

enter image description here

If you break as soon as you have exceeded pi, then you will break too early (after the first term, in fact!)

So your code should look like

function total = equation(n)
  total = 0;
  for i = 1:n
    total = total + (-1)^i / (2*i+1);
  end
  total = 4 * total;
end

Additionally, this series will only converge to pi if you start it at zero, rather than one -

function total = equation(n)
  total = 0;
  for i = 0:n
    total = total + (-1)^i / (2*i+1);
  end
  total = 4 * total;
end

Finally, you can simplify dramatically by vectorizing your code -

function total = equation(n)
  indices = 0:n;
  total = 4 * sum((-1).^indices ./ (2 * indices + 1));
end

回答2:


Your code does not make sense: why would you sum a single element, then discard the result the next cycle? Your purpose would be better served by:

function f = no_kitty_is_my_pi_you_cant_have_it(n)
        %'Sorry for the South Park reference/pun'

        k = 0:n;
        f = 4 * sum((-1).^k ./ (2*k+1));

end

And, as side note on MATLAB programming practices: choosing i and j as names for variables is not a good idea, because these two are built-in functions that give you the imaginary unit (the square root of -1).

回答3:


To add to the rest of the answers. This code will compute all the approximations of pi from n=1 to n=100.

n=100;
f=[];
for jj=1:n
    ii=0:jj;
    f=[f 4*sum( ((-1).^ii)./(2.*ii+1)  )];
end;
hold on
plot(f)
plot(1:size(f,2),ones(size(f))*pi)

enter image description here

标签:
© 2014 TuiCode, Inc.