4

我最近一直在尝试更多地了解 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 表达式?

4

3 回答 3

5

那这个呢:

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);
于 2008-11-13T21:08:12.137 回答
2

拉姆达波瓦!不确定这是否正确(没有 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; });
}
于 2008-11-13T21:15:40.920 回答
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...
于 2008-11-13T21:09:53.193 回答