I am trying to compute pi with a certain level of precision using the trapezoid method. However, I am encountering an error within my while loop, it is never ending. Does anyone know why?
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <iomanip>
#include <math.h>
#include <cmath>
usingnamespace std;
//******************************************************************************
// Limits of integration, number of steps, and the function to be integrated
constdouble A = 0;
constdouble B = 1;
double f(double x)
{
return sqrt(1 - x * x);
}
//******************************************************************************
int main()
{
double pidiff;
double prec;
double pi = 4 * atan(1);
cout << "What precision would you like?" << endl;
cin >> prec;
double answer; //final answer
double changex;
double xI;
double N = 1;
changex = (B - A) / N; //change in x formula
double sum = 0;
int i = 0;
int mintries = 1000;
while (true)
{
if (i == 0 || i==N)
{
xI = A + (i * changex); //xi formula
sum += f(xI); //add up all functions with xI
}
else
{
xI = A + (i * changex);
sum += 2 * f(xI); // same as above but need to multiply by 2.
}
i=i++;
answer = 2*changex * sum; // final answer
cout << answer << endl;
pidiff = abs(pi - answer);
cout << pidiff << endl;
N = N * 10;
if (pidiff <= prec && N>mintries)
{
break;
}
}
cout << answer << endl;
cout << N << endl;
cout << pi << endl;
system("pause");
return 0;
}
so you need to see what these values are:
if (pidiff <= prec && N>mintries)
to see why it did not stop.
print them out every iteration.
you can also force it to stop with a counter -- change the while loop to a for loop and stop after 100 iterations or something, with your printed debug values, to see what is going on without hassle. you can set it back to while-true later or you can keep the for loop to force it to stop after a while once you get a handle on # of iterations needed.
Well, each of the while loops should do one numerical integration ... but it doesn't.
Each numerical integration should start by resetting sum to 0, computing a new value for changex - you don't do either of those.
Each numerical integration should loop through i values from 0 to N - you don't do that.
N should be an integer of some sort, not a double.
If you integrate that f(x) between those limits you will get pi/4 - just saying; it's not clear whether your code is on the way to that or not.
There's just too many errors, @monicam. Why don't you start with a single numerical integration with the trapezium rule and get that right. You can sling a while() loop round it afterwards.