- #1
MathematicalPhysicist
Gold Member
- 4,699
- 373
i was asked to write down a code that calculates via the trapezoid method, the integral f(x)=10x^2-x^3 from x=-2.5 up to x=2, and compares it to the analytic solution. well here's my code, my problem is that it's stuck on numbers such as 20 (number of segments).
can anyone spot my error in my code, i appreciate:
can anyone spot my error in my code, i appreciate:
Code:
#include <stdio.h>
#include <math.h>
main()
{
long double initial,area,Segments,dx;
initial=-2.5;
area=0;
printf("insert the number of sgements to subdivide the interval \n");
scanf("%f", &Segments);
if(Segments!=0) dx=4.5/Segments;
else printf("error \n");
while(area<=84.515625 && initial<2)
{
area+=0.5*dx*((initial+dx)*(initial+dx)*10-(initial+dx)*(initial+dx)*(initial+dx)+initial*initial*10-initial*initial*initial);
if((fabs(area-84.515625))<0.001){
printf("the numerical integration yields %f with accuracy of 0.001 from analytical result \n",area);
break;
}
initial+=dx;
}
}