Hi, im trying to code a function that takes the integral of a given function usi
ID: 3825325 • Letter: H
Question
Hi, im trying to code a function that takes the integral of a given function using trapezoidal rule, but I cant get the code to give the right answer.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
int n;
char q;
float a, b;
double integrate(double a, double b, int n) //Evaluates the Integral
{
int i;
float x;
float k = (b - a) / n;
float l = (b + a) / 2;
float v;
for (i = 1; i < n; i++) {
x = b + k * i;
v = l + f(x);
}
return l*k;
}
double f(double x)
{
float h;
h = x;
(x)= sin(h) + ((h*h) / 10);
}
When a is set to -2.1, b set to 1.5 and N set to 15, the given answer is -0.07200, however the answer should be -0.14816
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
int n;
char q;
float a, b;
double integrate(double a, double b, int n) //Evaluates the Integral
{
int i;
float x;
float k = (b - a) / n;
float l = (b + a) / 2;
float v;
for (i = 1; i < n; i++) {
x = b + k * i;
v = l + f(x);
}
return l*k;
}
double f(double x)
{
float h;
h = x;
(x)= sin(h) + ((h*h) / 10);
}
Explanation / Answer
// C program to implement Trapezoidal rule
#include<stdio.h>
#include <math.h>
double y(double x)
{
float h;
h = x;
x= sin(h) + ((h*h) / 10);
return x;
}
//Evaluates the Integral
float integrate(double a, double b, double n)
{
// Grid spacing
float h = (b-a)/n;
// Computing sum of first and last terms
// in above formula
float s = y(a)+y(b);
// Adding middle terms in above formula
int i;
for (i = 1; i < n; i++)
s += 2*y(a+i*h);
// h/2 indicates (b-a)/2n. Multiplying h/2
// with s.
return (h/2)*s;
}
// Driver program to test above function
int main()
{
// Range of definite integral
double x0 = -2.1;
float xn = 1.5;
// Number of grids. Higher value means
// more accuracy
int n = 15;
printf("Value of integral is %6.4f ",
integrate(x0, xn, n));
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.