Write a program to calculate an approximate integral of the function f(x) = 0.1x
ID: 3797179 • Letter: W
Question
Write a program to calculate an approximate integral of the function f(x) = 0.1x^3 + 1 over the interval [a, b] using the trapezoidal method with n subintervals, where a, b, and n are taken from standard input. In lecture 5, you learned how to calculate an approximate integral using the rectangle rule. In this problem, you will use the trapezoidal rule to approximate the integral (see Figure 1). At the start of the program, prompt the user to input the interval bounds and the number of subintervals by printing "Integrate over [A, B] with N subintervals. Input A B N: ". If BExplanation / Answer
Code:
#include<stdio.h>
#include<math.h>
float my_pow(float base,int exp)
{
int i=0;
float x=1;
for(i=0;i<exp;i++)
x= x*base;
return x;
}
float my_func(float x)
{
float y= (0.1 * my_pow(x,3)) + 1;
return y;
}
//Approximation using trapezoidal rule
float approx_integral(float a, float b, int n)
{
float step=(b-a)/n;
float x=a;
float val=0;
printf("Step:%f ", step);
val= val+ my_func(x); //For x=a f(a)
for(int i=1;i<=n;i++)
{
x+=step;
if(i!=n)
val= val+ 2.0 * my_func(x);
if(i==n)
val = val + my_func(x);
}
val= (step/2.0) * val;
return val;
}
int main(void)
{
float a,b;
int n;
printf("Input a,b,n:");
scanf("%f %f %d", &a,&b,&n);
if(a>b){
printf("A must be less than or equal to b ");
return 0;
}
if(n<0){
printf("n must be non-negative ");
return 0;
}
printf("Integration result:%.3f ",approx_integral(a,b,n));
return 0;
}
Output:
$ ./a.out
Input a,b,n:0 1 2
Step:0.500000
Integration result:1.031
$ ./a.out
Input a,b,n:-10 10 100
Step:0.200000
Integration result:19.999
$ ./a.out
Input a,b,n:0 0 12
Step:0.000000
Integration result:0.000
$ ./a.out
Input a,b,n:1 10 100
Step:0.090000
Integration result:258.995
$ ./a.out
Input a,b,n:0 10 100
Step:0.100000
Integration result:260.025
$ ./a.out
Input a,b,n:15 10 -1
A must be less than or equal to b
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.