Reputation: 213
I feel incredible stupid that I have to ask this question, but everyone was a noob once. Right?!?
For an assignment we have to implement the following sum:
PI - 3 = sum from i=1 to N of (-1)^(i+1) / i(i+1)(2i+1) (shame about the lack of Mathjax here)
So in Java:
public static double[] computeSumOfPi(int N) { //returns the value of PI computed
//with N terms of the sum and the
//last added term
double term = 0;
double sum = 0;
double[] result = new double[2];
for(int i = 1; i < N + 1; i++) {
term = Math.pow((-1),(i+1)) / i*(i+1)*(2*i+1);
sum = sum + term;
}
result[0] = sum + 3;
result[1] = term;
return result;
}
In Matlab I tried the following
function [sumPi, lastTerm ] = sumForPi( n ) %sumForPi.m
for i = 0 : n
term = (-1)^(i+1) / (i*(i + 1)*(2*i + 1));
temp = temp + term;
end
sumPi = temp + 3.0;
lastTerm = term;
end
Which I try to invoke:
>> sumForPi(20)
Which returns the following error:
undefined function or variable "temp"
Error in sumForPi (line 4)
temp = temp + term;
I would be delighted if someone could point out my (probably simple) mistake.
Thanks in advance!
Upvotes: 1
Views: 83
Reputation: 5126
You need to declare the initial value of temp
before you read it. Hence, try to include temp = 0;
before the loop, i,e.
function [sumPi, lastTerm ] = sumForPi( n ) %sumForPi.m
temp = 0;
for i = 0 : n
term = (-1)^(i+1) / (i*(i + 1)*(2*i + 1));
temp = temp + term;
end
sumPi = temp + 3.0;
lastTerm = term;
end
Upvotes: 2