1

I am new to matlab, and am trying to write a script for this equation for n=100:

enter image description here

And am using this:

n = 100; % set number of terms
sum = 1; % starting point of the sum
sign = 1; % an integer +/- 1
for k = 1 : n % forloop - loops k from 1 to n
    term = sign/(k^2); % compute the term
    sum = sum + term; % update the rolling sum
    sign = - sign; % flip the sign
end;
disp(n); % print n
disp((12*sum)^(0.5)); % print the approximation to pi
disp((12*sum)^(0.5)-pi); % print the error

But this is returning some strange values:

100 - fine

    4.6764 ????

    1.5348 ????

Would anyone be able to point out the mistake I made? I have a feeling it might be the way I raised the sum to the power of 0.5, but am not entirely sure.

Thanks

elbarto
  • 3,356
  • 3
    This is your error: initialize with sum = 0. – Stephen Montgomery-Smith Mar 14 '15 at 02:38
  • Thanks @StephenMontgomery-Smith, this was indeed the error. I am curious though, since the sum begins from $k=1$ why do we set the sum from starting at $0$ ? – elbarto Mar 14 '15 at 02:41
  • 4
    Write a simple program to compute $\sum_{k=1}^3 k$. Then go step by step through the program to predict what the computer will do. Then it should become clear to you. – Stephen Montgomery-Smith Mar 14 '15 at 02:48
  • You should read how to debug small programs It leads you through some steps stolen from debugging larger programs because they work. There is a tendency to ignore good practice on small programs because they are small and "the overhead isn't worth it". That is fine when it works. If it doesn't-do the careful stuff to make it work. – Ross Millikan Mar 14 '15 at 03:06
  • Thanks guys, you have equipped me well for my journey to introductory matrix laboratory! :D

    Helping those in need makes you larger than life.

    – elbarto Mar 14 '15 at 03:16
  • Alright, got it. the $\text{sum} \space = 0$ term is not related to the index $k$ at all. It is just the starting value for the sum! – elbarto Mar 14 '15 at 03:24

0 Answers0