public double Integral(double[] x, double intPointOne, double intPointTwo)
{
double integral = 0;
double i = intPointOne;
do
{
integral += Function(x[i])*.001;
i = i + .001;
}
while (i <= intPointTwo);
return integral;
}
这是一个函数,我必须简单地使用部分求和来集成 x1-x2 中的一个函数。我怎样才能使这个循环更有效(使用更少的循环),但更准确?
Function
在每次迭代中都会发生变化,但它应该是无关紧要的,因为它的数量级(或边界)应该保持相对不变......
最佳答案
1) 查看 http://apps.nrbook.com/c/index.html 的第 4.3 节对于不同的算法。
2) 要控制精度/速度因子,您可能需要指定边界 x_low
和 x_high
以及您希望积分中的切片数。所以你的函数看起来像这样
// Integrate function f(x) using the trapezoidal rule between x=x_low..x_high
double Integrate(Func<double,double> f, double x_low, double x_high, int N_steps)
{
double h = (x_high-x_low)/N_steps;
double res = (f(x_low)+f(x_high))/2;
for(int i=1; i < N; i++)
{
res += f(x_low+i*h);
}
return h*res;
}
一旦您理解了这种基本集成,您就可以继续使用 Numerical Recipies 和其他资源中提到的更精细的方案。
要使用此代码,请发出类似 A = Integrate( Math.Sin, 0, Math.PI, 1440 );
的命令
关于c# - 更高效的集成循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10741824/