# Thread: Numerical Integration by Trap Rule.

1. ## Numerical Integration by Trap Rule.

Currently attempting to do a numerical integration using the Trap rule.

Original integral was

cos(x)/sqrt(x)

between 0 and infinity.

With some subsitution and what not, have got it to

cos(x^2), which obviously is a fresnel integral.

My code currently looks like this, but it will only complete 1 iteration. I cannot work out why it will only complete 1 loop and give a totally wrong answer.

Code:
```#include <stdio.h>
#include <math.h>

main()
{
int n,i;
double x1,xn,h,new,old,sum,y,x,accuracyreq,accuracy;

printf("Input Accuracy:");
scanf("%lf",&accuracyreq);

printf("\nInput Upper Limit Value (Larger is More Accurate):");
scanf("%lf",&xn);

printf("The following is the answer to the integral cos(x)/sqrt(x): ");
accuracy=0;
new=2;
sum=0;
x=x1;
old=0.5;

for(n=10000000;accuracy>accuracyreq;n++)
{
h=xn-x1/(n-1);

for(i=0;x<xn;i++)
{

y=2*cos(pow(x,2));
if(x==x1||x==xn){
y=y/2;
}
sum=sum+y;
x=x+h;
}

new=sum*h;
accuracy=new/old;

printf("Accuracy is %lf",accuracy);
}

printf("%lf\n",new);
printf("%d\n",i);
printf("%d\n",n);
int end;
scanf("%d",&end);
}```

2. accuracy>accuracyreq

for loop runs while condition is true

you set accuracy to 0, and I suppose enter some positive value to the accuracyreq

so the condition is never true and your loop should not run at all

3. Good point, it doesnt run the initial loop in which accuracy would be set to some other number (greater then 0 and greater then accuracyreq).

Having changed that, there appears to be an infinite loop (or else, my program takes 1+minute to run.)

Any ideas?

Ok, Update.

I have realized that when I input my accuracyreq, I am inputting it in the form of 0.999999 being very accurate and 0.000001 being very inaccurate. therefore, I have switched accuracy>accuracyreq into accuracyreq>accuracy meaning my loop will run while my accuracy is less then the accuracyreq.

It is now running, but when I printf my number of iterations and step number, the step number remains 3 (which is the initial step number, it isnt incrementing) and the iteration number comes out fairly large (over 20,000).

Not sure where to go next.

Current Code.

Code:
```#include <stdio.h>
#include <math.h>

main()
{
int n,i;
double x1,xn,h,new,old,sum,y,x,accuracyreq,accuracy;

printf("Input Accuracy:");
scanf("%lf",&accuracyreq);

printf("\nInput Upper Limit Value (Larger is More Accurate):");
scanf("%lf",&xn);

printf("The following is the answer to the integral cos(x)/sqrt(x): ");
accuracy=100;
new=2;
sum=0;
x=x1;
old=0.5;

for(n=3;accuracy<accuracyreq;n++)
{
h=xn-x1/(n-1);

for(i=0;x<xn;i++)
{

y=2*cos(pow(x,2));
if(x==x1||x==xn){
y=y/2;
}
sum=sum+y;
x=x+h;
}

new=sum*h;
accuracy=new/old;

//printf("Accuracy is %lf",accuracy);
}

printf("%lf\n",new);
printf("%d\n",i);
printf("%d\n",n);
int end;
scanf("%d",&end);
}```

4. I dont think you are initializing x1, this could be a cause for trouble.