Using C++ Programming C-code to integrate f(x) = e^(-x^2) elementof [- infinity,
ID: 3818358 • Letter: U
Question
Using C++ Programming C-code to integrate f(x) = e^(-x^2) elementof [- infinity, infinity] Use N of diff values, N number of steps/intervals. Print out all x_i, f_i =f(x_i) and the result. Determine and print the appropriate value of N based on the results for different N values. Integrate the function by both Simpson and Trapezoidal rule, then compare the results with it calculated from mathematical software such as Matlab! C-code must contain: 1) use of arrays 2) use of pointers 3) use of structure 4) use of union 5) use of functions and function calls 6) formatted output on screen 7) saving of the same output on a data file
Explanation / Answer
c code for trapezoidal rule
#include<stdio.h>
#include<conio.h>
#include<math.h>
float f(float x)
{
return(exponential*pow(sq x)));
}
void main()
{
int i,n;
float x0,xn,h,y[20],so,se,ans,x[20];
printf(" Enter values of x0,xn,h: ");
scanf("%f%f%f",&x0,&xn,&h);
n=(xn-x0)/h;
if(n%2==1)
{
n=n+1;
}
h=(xn-x0)/n;
printf(" refined value of n and h are:%d %f ",n,h);
printf(" Y values ");
for(i=0; i<=n; i++)
{
x[i]=x0+i*h;
y[i]=f(x[i]);
printf(" %f ",y[i]);
}
so=0;
se=0;
for(i=1; i<n; i++)
{
if(i%2==1)
{
so=so+y[i];
}
else
{
se=se+y[i];
}
}
ans=exponential*pow(sq x);
printf(" final integration is %f",ans);
getch();
}
c code for simpson 1/3rd rule
#include<stdio.h>
#include<conio.h>
float f(float x)
{
return(exponential*pow(sq x));
}
void main()
{
int i,n;
float x0,xn,h,y[10],so,se,ans,x[10];
printf(" Enter values of x0,xn,h: ");
scanf("%f%f%f",&x0,&xn,&h);
n=(xn-x0)/h;
if(n%2==1)
{
n=n+1;
}
h=(xn-x0)/n;
printf(" Refined value of n and h are:%d %f ",n,h);
printf(" Y values: ");
for(i=0; i<=n; i++)
{
x[i]=x0+i*h;
y[i]=f(x[i]);
printf(" %f ",y[i]);
}
so=0;
se=0;
for(i=1; i<n; i++)
{
if(i%2==1)
{
so=so+y[i];
}
else
{
se=se+y[i];
}
}
ans=exponential*pow(sq x);
printf(" Final integration is %f",ans);
getch();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.