- #1
ggeo1
- 63
- 0
c++ simpson's method --loop doesn't stop
Hello, i have done the simpson's method and it works fine.My problem is that it doesn't stop when it gives me the desired result but the loop continues for ever..
I have done other methods too like that and they stop,but this one not.
Thanks!
Hello, i have done the simpson's method and it works fine.My problem is that it doesn't stop when it gives me the desired result but the loop continues for ever..
Code:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <iomanip>
#include <cmath>
using namespace std;
double f(double x){
double y;
y=sqrt(x-0.1);
return y;
}
double simpson (double down,double up,int n){
double h,sumeven,sumodd,all,result;
h=(up-down)/n;
sumeven=0.0;
for (int i=1;i<=n/2.0-1.0;i++){
sumeven+=f(down+2.0*i*h);//coefficients
}
sumodd=0.0;
for (int i=1;i<=n/2.0;i++){
sumodd+=f(down+h*(2.0*i-1.0));//coefficients
}
all=4*sumodd+2*sumeven;
result=(h/3.0)*(f(down)+f(up)+all);
return result;
}
int main()
{
double eps=1e-6;//accuracy
double exact=1.1767695;//exact solution for the integral
double error=1.0;
double result;
int n=1;//initial point
result=simpson(1.0,2.0,n);
while (fabs(error-exact)>eps) {
result=simpson(1.0,2.0,n);
cout <<"\nFor n = "<<n<<",error = "<<fabs(error-exact)<<",value = "<<result;
n++;
}
return 0;
}
I have done other methods too like that and they stop,but this one not.
Thanks!