T
T
tr1ck2014-07-13 18:59:37
Programming
tr1ck, 2014-07-13 18:59:37

How to calculate integral by trapezoidal method (c++ and scilab)?

I'll start in order. There is an integral of the function f(x) =2x/sqrt(1-x^4) with limits from 0 to 1. Calculate with accuracy E=10^(-9). Actually the question is what kind of accuracy and how to register it in the code? What to do with border 1? After all, with 1 => 'inf'. The teacher said to subtract some minimum number p so that it is not 1, but then you need to change the accuracy of E and it will be equal to, like E (initial) + E (p), right? And how to write it in something, I didn’t really figure it out with this accuracy, here is my code, which is quite easy to understand:
#include "stdafx.h"
#include
#include
#include
using namespace std;
float f(float x)
{
return 2 * x / sqrt (1-x*x*x*x);
//return x / exp(x);
}
int _tmain(int argc, _TCHAR* argv[])
{
float a = 0, b = 0.9999999, n = 4, S = 0, h, integ;
h = (b - a) / n;
for (int i = 1; i <= (n - 1); i++)
S += f(a + h*i);
integ = h * ((f(a) + f(b)) / 2 + S);
cout << integ;
getchar();;
return 0;
}
And the second question, is it hard to transfer to scilab?) I have never used it yet, but time is shaking)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2014-07-13
@Rsa97

Hmm ... You definitely did not understand the accuracy. We need to add one more outer loop, in which the number of partitioning steps n will increase until the change in the value of the integral between the previous and current iterations of the loop becomes less than the specified accuracy.

n = 2;
I = (f(a)+f(b))/2*(b-a);
do {
    Iprev = I;
    // здесь считаем интеграл I при разбиении на n отрезков
    n++;
} while (abs(Iprev-I) > precision);

M
Misha Krinkin, 2014-07-13
@kmu1990

Well, with errors, there are two options:
1. exact a priori estimate, not your case, simply because 1 is the break point, the closer to it, the more derivatives become and the estimate will again give infinity;
2. consistently reduce the integration step (halve) and look at the difference between the results of the current and previous steps, as soon as the difference falls within the error, you can stop - this is done if there are no better options.
Regarding the upper bound, I do not think that it is required to take into account this error in the calculations, simply because the error estimate for option 2 is already inaccurate. But you can again iteratively reduce the indent from the upper bound until the difference between iterations becomes small enough.
UPD. Regarding the transfer to scilab, apparently everything is rather clumsy:
www.ibm.com/developerworks/ru/library/l-scilab1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question