Area under a curve

Hi there,

I'm trying to write a program to calculate and output area under the curve y = 0.6x^2 + 4 to 12 decimal places.

I want the program to calculate the area using (1)upper limit method (2) lower limit method (3) the midpoint method as well as (4) the trapezoidal method.

I also want the program to calculate for three different segment values, n = 5, 50, and 500.

I understand the basics of functions, calling:
double f (double x)
{
return 0.6*pow(x,2) + 4
}


But I haven't the slightest clue how to program for all four methods mentioned above. Any help would be greatly appreciated.


What I currently have;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// This program calculates and displays area under a curve using LL, UL, MP, and trapedzoidal methods

#include <iomanip>
#include <iostream>
#include <math.h>


using namespace std;
	double f(double x)
	{
     return 0.6*pow(x,2) +5;
	}
int main ( ) 
{

double a, b, delx, x, area;
int n;

cout << "Welcome. To begin, please enter a value for 'a' followed by a value for 'b'. \n";
cin>>a>>b;
cout << "You have entered a = " << a<<" & b = " <<b <<". Now, input an n value \n";
cin >>n;

delx = (b-a)/n;
area = (f(a)+f(b))/2;

    for (int i=1;i<n;i++) 
		{
        area += f(a+i*delx);
        area = area*delx;
    
		}

cout << "The area under the curve of f(x) = 0.6x^2 + 4 is ";
cout << setprecision(12) << area;
	

	
}
Line 11
Typo.
 
return 0.6*pow(x,2) +5;

edit: I'm blind.
Also, you haven't specified the range in which to calculate the area over.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
	// n can not be negative, so use unsigned int
	constexpr uint32_t n{ 5 };
	constexpr double a{ 0.0 }, b{ 4.0 }, deltaX{ (b - a) / n };

	// to store the function values
	std::vector<double> fxValues;
	// calculate function values
	// n segment values = n+1 function values
	/*
	Function values, in case you can't see the pattern
	deltaX = 0.8, btw
	f( 0 ), f( 0.8 ), f( 1.6 ), f( 2.4 ), f( 3.2 ), f( 4.0 )
	*/
	for( uint32_t i{}; i < n + 1; i++ ) {
		fxValues.push_back( f( deltaX * i ) );
	}

	/*
	Trapezoidal Rule mnemonic
	area = deltaX/2 * ( (first + last) + 2*rest )
	*/
	double rest{};
	// not including first and last values
	for( uint32_t i{ 1 }; i < n - 1; i++ ) {
		rest += fxValues[i];
	}
	double area{ deltaX / 2 * ((fxValues.front( ) + fxValues.back( )) + 2 * rest) };

	std::cout << "Area = " << std::fixed << std::setprecision( 12 ) << area << "\n";


Area = 20.940800000000

http://cpp.sh/34awp

Integrating it gave me 28.8.
Last edited on
Are the LL, UL, MP the same as the left sum, right sum and midpoint sum links in:
http://www.dummies.com/how-to/content/how-to-approximate-area-with-the-trapezoid-rule0.html
Topic archived. No new replies allowed.