Important: Please read the Qt Code of Conduct -

[SOLVED] Integrate a function between a and b

  • Hi!

    I want to integrate a function between the lower boundary "a" and the upper boundary "b".

    I have got:

    inline double integrate(double(*f)(double), double a, double b)
        double sum = 0;
        double n = 20;
        double result = (b-a)/n;
        for (double k = 1.; k < n-1; k+=1.)
        sum += f(a + k*result);
        return result * ((f(a) + f(b)) / 2 + sum);
    and in mainwindow.cpp (in the void function):
              double cp = lineEdit->text().toDouble(&ok);
              double x;
              double a=.025;
              double b=.075;
              double function=1-(cp*(1-x)); 
              double integrateresult = integrate(function, a, b);

    But it does not integrate the function...

    Does someone see the mistake?
    Please share!
    Thanks in advance!

  • Moderators

    integrate() expects a pointer to function and you are giving it a double called "function". Naming a variable "function" does not make it a function :)

    In this code "function" variable is not a function. It's a variable of type double and undefined value (undefined because you never gave value to x so the result is garbage).

  • Hello @Chris-Kawa !

    Thanks for pointing out some problems.

    I have done some improvements and the following code compiles without any problem:
    in the header-file:

    inline double f(double x)
         return x*x;

    in mainwindow.cpp in the function which is emitted with a QPushButton:

                double aB = .1;
                double bB = 2;
                int n = 10000;
                double h = (bB-aB)/n;
                double area = (f(aB)+f(bB))/2;
                for (int i=1;i<n;i++)
                    area += f(aB+i*h);
                QString resultString = "";

    Furthermore, it even calculates the "area" and gives the result "14033.3". This is unrealistically high and incorrect!

    Mathematica gives me for the integration of the same equation:
    integral_0.1^2 x^2 dx = 2.66633
    which is correct!

    If someone has a helpful idea, please share!

  • Solved!

    area = area*h; 

    was missing after the for-loop!

    Now the result is: 2.66633
    the same is with Mathematica: 2.66633
    (For math-friends: at least approximately, if not "too" many digits are compared; Nevertheless setting "n" from "n=10000" to a higher accuracy, the area will be approximated more correctly!)

    Thanks anyway! :-)

  • @newe12 said:

    double h = (bB-aB)/n;
    double area = (f(aB)+f(bB))/2;

    What is h for?
    And why are you starting the area with the average value of the two boundary points?

    Shouldn't it be more like:

     area += f(interval*i)

    where i goes from boundary to boundary and interval is .1?

Log in to reply