T
T
tr1ck2014-07-17 18:36:28
Programming
tr1ck, 2014-07-17 18:36:28

Error in simple code?

#include "stdafx.h"
#include <iostream>
#include <conio.h>
#include <math.h>

using namespace std;

double f(double x)
{
  double  S = 1, R = 0, N, n, y, Y = 1, F = 1;
  for (int i = 0; i < 10; i++){
    n = i + 1;
    y = -(1/2) + 1 - n;
    Y = Y*y;
    F = F*n;
    N = (pow(x,n)*pow(-1,n)*(Y))/F;
    S = S + N;
  }





  return S*(2 * x / sqrt ((1+x)*(1+x*x)));
}

int _tmain(int argc, _TCHAR* argv[])
{
  setlocale(LC_ALL, "Russian");
  cout << "Программа считает интеграл 2x/sqrt(1-x^4) с границами от 0 до 1 методом трапеции";
  cout << "с точность E=10^(-9)!" << endl;
  double a = 0, b = 1, n = 4, S = 0, h, integ, IntegPrev;
  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);
  //посчитали первый интеграл для n=4
  do {
    IntegPrev = integ;
    n += 1;
    h = (b - a) / n;
    S = 0;
    for (int i = 1; i <= (n - 1); i++)
      S += f(a + h*i);
    integ = h * ((f(a) + f(b)) / 2 + S);
  } while (abs(IntegPrev - integ) > 0.000000001);
  cout << "\nAnswer: " << integ << endl;
  getchar();
  return 0;
}

It always gives the same answer when I change values ​​in the for loop. That is, up to 50, 150, 500, etc. Although the values ​​should be different, because the more I summarize, the more accurate the answer should be. And what is most interesting, I even put a negative number there for (int i = 0; i < -101; i++){...}, it will still give the same answer, what for? Then the loop shouldn't work at all.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Misha Krinkin, 2014-07-17
@tr1ck

If you are talking about the for loop inside the function f, then of course it will always count the same S, simply because when i = 0, you count n = 1, then y = 0 and, accordingly, Y = 0 from here and for all further iterations loop, respectively, you always add 0 to S, i.e. S regardless of the number of iterations == 1.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question