[英]Matlab and functions
我不得不问这个问题,真是太不可思议了,但是每个人都曾经是菜鸟。 对?!?
对于一个分配,我们必须实现以下总和:PI-3 =从i = 1到(-1)^(i + 1)/ i(i + 1)(2i + 1)的N的总和(对于缺乏这里的Mathjax)
因此在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;
}
在Matlab中,我尝试了以下方法
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
我尝试调用:
>> sumForPi(20)
返回以下错误:
未定义的函数或变量“ temp”
sumForPi错误(第4行)
temp =温度+项;
如果有人可以指出我的(可能是简单的)错误,我将非常高兴。
提前致谢!
您需要在读取前声明temp
的初始值。 因此,尝试包括temp = 0;
在循环之前,即
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.