我最近一直试图更多地了解lambda表达,并想到了一个有趣的练习......
有没有办法简化这样的c ++集成函数:
// Integral Function
double integrate(double a, double b, double (*f)(double))
{
double sum = 0.0;
// Evaluate integral{a,b} f(x) dx
for(int n = 0 ; n <= 100; ++n)
{
double x = a + n*(b-a)/100.0;
sum += (*f)(x) * (b-a)/101.0;
}
return sum;
}
使用c#和lambda表达式?
答案 0 :(得分:6)
这个怎么样:
public double Integrate(double a,double b, Func<double, double> f)
{
double sum = 0.0;
for (int n = 0; n <= 100; ++n)
{
double x = a + n * (b - a) / 100.0;
sum += f(x) * (b - a) / 101.0;
}
return sum;
}
测试:
Func<double, double> fun = x => Math.Pow(x,2);
double result = Integrate(0, 10, fun);
答案 1 :(得分:2)
Lambda Powa!不确定这是否正确(没有C#程序员!只是喜欢它的lambda东西)
(a, b, c) => {
double sum = 0.0;
Func<double, double> dox = (x) => a + x*(b-a)/100.0;
// Evaluate integral{a,b} f(x) dx
for(int n = 0 ; n <= 100; ++n)
sum += c(dox(n)) * (b-a)/101.0;
return sum;
}
好的,所以我认为虽然代码是C ++,为什么不保留它C ++并获得lambda?这就是它如何查找c ++ 0x,希望很快就会以标准形式发布:
static double Integrate(double a, double b, function<double(double)> f)
{
double sum = 0.0;
// Evaluate integral{a,b} f(x) dx
for(int n = 0; n < 100; ++n) {
double x = a + n * (b - a) / 100.0;
sum += f(x) * (b - a) / 101.0;
}
return sum;
}
int main() {
Integrate(0, 1, [](double a) { return a * a; });
}
答案 2 :(得分:0)
如上所述,真正的力量来了。例如,在C#
中 static double Integrate(double a, double b, Func<double, double> func)
{
double sum = 0.0;
// Evaluate integral{a,b} f(x) dx
for(int n = 0 ; n <= 100; ++n)
{
double x = a + n*(b-a)/100.0;
sum += func(x) * (b - a) / 101.0;
}
return sum;
}
然后:
double value = Integrate(1,2,x=>x*x); // yields 2.335
// expect C+(x^3)/3, i.e. 8/3-1/3=7/3=2.33...