Saturday, February 19, 2011

Lambda expression exercise

I have been trying to learn more about lambda expressions lately, and thought of a interesting exercise...

is there a way to simplify a c++ integration function like this:

// 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;
}

by using c# and lambda expressions?

From stackoverflow
  • What about this:

    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;
    }
    

    Test:

        Func<double, double> fun = x => Math.Pow(x,2);        
        double result = Integrate(0, 10, fun);
    
    Marc Gravell : hehe - within seconds of each other ;-p
  • The real power comes, as stated, when calling it. For example, in 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;
        }
    

    Then:

        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...
    
  • Lambda Powa! Not sure whether this is right (No C# programmer! Just liking its lambda stuff)

    (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;
    }
    

    Ok, so i think while the code is C++, why not keep it C++ and get lambda in? Here it is how it looks for c++0x, being hopefully released as a Standard very soon :

    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; });
    }
    

0 comments:

Post a Comment