[ Prev | Index | Next ]
Japanese English
Now Loading...
Download
Please download on PC (not smartphone) and extract the ZIP file. Then double-click VCSSL.bat (batch file) to execute for Microsoft® Windows®, or execute VCSSL.jar (JAR file) on the command line for Linux® and other OSes.
For details, see How to Use.
You are free to use and modify this program and material, even for educational or commercial use. » Details

Numerical Integration Using the Trapezoidal Method (Trapezoidal Approximation)

In this VCSSL program, we continue from the previous article on the rectangular method to numerically calculate the value of an integral.

This time, we go one step further and use trapezoids to approximate the small areas under the curve. Although the actual change in the code is just a single line, the resulting improvement in accuracy is quite dramatic.

- Table of Contents -

Note: As with previous articles, this program is a sample code meant for explaining the algorithm, so it does not include any advanced GUI features. To change the integrand function or parameters, please modify the code directly.

The code is written in VCSSL, but you're welcome to port it to another language if you prefer. (We've also included C version and C++ version code samples below.) This code is released into the public domain (CC0), so you are free to use it at your own risk.

[ Articles in the Numerical Integration Series ]

How to Use

Download and Extract

At first, click the "Download" button at the above of the title of this page by your PC (not smartphone). A ZIP file will be downloaded.

If you are using Windows, right-click the ZIP file and choose "Properties" from the menu, and enable "Unblock" checkbox at the right-bottom (in the line of "Security") of the properties-window. Otherwise, when you extract the ZIP file or when you execute the software, security warning messages may pop up and the extraction/execution may fail.

Then, please extract the ZIP file. On general environment (Windows®, major Linux distributions, etc.), you can extract the ZIP file by selecting "Extract All" and so on from right-clicking menu.

» If the extraction of the downloaded ZIP file is stopped with security warning messages...

Execute this Program

Next, open the extracted folder and execute this VCSSL program.

For Windows

Double-click the following batch file to execute:

VCSSL__Double_Click_This_to_Execute.bat

For Linux, etc.

Execute "VCSSL.jar" on the command-line terminal as follows:

cd <extracted_folder>
java -jar VCSSL.jar

» If the error message about non-availability of "java" command is output...

After Launching

When launched, the program runs the numerical integration process, displays the graph of the integrated function, and prints the resulting integral value to the console.
Graph

Modifying the Integrand or Parameters

To change the integrand function, integration interval, or accuracy, open the program file "IntegralTrapezoidal.vcssl" in a text editor and modify the code as needed.

Topic Overview

Quick Recap of the Previous Article

This article builds upon what we covered in the previous article. Let's do a quick review. If you want to solidify your understanding, feel free to read the previous article first:

In the previous article, we calculated the value of a definite integral by approximating the area between the x-axis and \( y = f(x) \) using thin rectangles. Here's the visual representation: /p>

Area divided into \(n\) long, thin rectangles
Area divided into \(n\) long, thin rectangles
By summing the areas of these rectangles, you can approximately compute the area between the function \(f(x)\) and the \(x\)-axis -- that is, the integral value.

As we saw, the area between the \(x\)-axis and the curve \(y = f(x)\) is theoretically equal to the definite integral of \(f(x)\).

This means we don’t need to solve the integral analytically -- as long as we can compute the area numerically with a program, we can obtain the integral value.

However, this method inevitably introduces error, as shown in the diagram. That's because we're approximating a curved area using rectangles, which naturally results in overestimation or underestimation -- gaps and overlaps that lead to error.

How Can We Reduce That Error?
-- From Rectangles to Trapezoids

Now let's dive into the main topic of this article.

Looking again at the previous diagram, you might ask: "How can we quickly reduce this error?" A natural idea is to make the rectangles thinner -- i.e., increase the number of subdivisions.

In fact, if you try it out, you'll see that the error decreases roughly in proportion to the rectangle width (see previous article).

But beyond a certain point, making them thinner results in diminishing returns: the number of calculations skyrockets, other types of error (like rounding) begin to accumulate, and the required computation time increases.

So here's the key question: Can we reduce the error more effectively -- without increasing the number of subdivisions? Let's try switching from rectangles to trapezoids to approximate the area between the x-axis and \(y=f(x)\):

Area divided into n long, thin trapezoids
Area divided into \(n\) long, thin trapezoids
By summing the areas of trapezoids instead of rectangles, we can approximate the area between \(f(x)\) and the x-axis (i.e., the integral value) more accurately.

If you compare this diagram with the one using rectangles, you can clearly see that the gaps and overlaps are smaller, and the approximation looks much closer to the actual curve.

As it turns out, this method -- known as the trapezoidal method (trapezoidal approximation) -- can dramatically reduce error compared to the rectangular method.

Now let's get into the actual calculation.

Just like before, we divide the interval from \(a\) to \(b\) into \(n\) segments (trapezoids).
We define:
\[ \Delta x = (b - a) / n \] \[ x_i = a + i \Delta x \]
Each trapezoid has a base width of \(\Delta x\), and the area of the i-th trapezoid is calculated using:
\[ \textrm{Area of i-th trapezoid} = \frac{ (\textrm{Height}_{Left} + \textrm{Height}_{Right} ) \times \textrm{Width} }{ 2 } \] \[ = \frac{ ( f(x_i) + f(x_{i+1}) ) }{ 2 } \Delta x \] \[ = \frac{ ( f(x_i) + f(x_i + \Delta x) ) }{ 2 } \Delta x \]
Then we sum the areas of all trapezoids:
\[ \textrm{Total area (integral value)} = \sum_{i=0}^{n-1} \frac{ ( f(x_i) + f(x_i + \Delta x) ) }{ 2 } \Delta x \]
As you can see, this is only a slight change from the previous method -- and in fact, the required change to the program code is just as small.

Code

Let's take a look at the actual code for performing numerical integration using the **trapezoidal method (trapezoidal approximation)**.

The program is written in VCSSL, which has a syntax somewhat similar to C, so it should feel fairly intuitive to read.

In addition, we've included equivalent implementations in C and C++ below as well.

Want to plot the results of the C/C++ versions?
The VCSSL version automatically generates a graph when you run it, but the C and C++ versions only print numerical results to standard output. If you'd like to visualize the results from C/C++, you can redirect the output to a file and open it with a graphing tool (such as RINEARN Graph 2D to create a plot.

Full Code Listing

Let's begin with the full code written in VCSSL. It's fairly short -- under 50 lines in total:


coding UTF-8;         // Specify character encoding to avoid mojibake
import Math;          // Import math library
import tool.Graph2D;  // Import graphing library


// Parameter constants for the calculation
const double A = 0.0;  // Lower bound of the integration interval
const double B = 1.0;  // Upper bound of the integration interval
const int N = 10;      // Number of subdivisions (higher = more accurate)

// Function to integrate: f(x) = cos(x)
double f(double x) {
	return cos(x);
}

// ------------------------------------------------------------
// Numerical integration using the trapezoidal method
// ------------------------------------------------------------

double delta = (B - A) / N;  // Width of each trapezoid: Delta x
double value = 0.0;          // Final result (total area)

for(int i=0; i<N; i++) {
	
	// X value at the bottom-left of the i-th trapezoid
	double x = A + i * delta;
	
	// Print partial result up to the i-th point
	println(x, value); // (Comment out if N is large)
	
	// Add the i-th trapezoid's area to the total
	value += ( f(x) + f(x+delta) ) * delta / 2.0;
}

// Output the final integral value
println(B, value);

// Plot the results on a graph
// (Comment out if N is large)
setGraph2DData(newGraph2D(), load());
IntegralTrapezoidal.vcssl

That's the full code.

Here's the overall structure: You first define the integrand and parameters, then use a for loop in the middle section to compute the integral, and finally plot the results.

Note on double type in VCSSL:
Although "double" is used here, VCSSL treats "double" and "float" as equivalent. Both are handled as double-precision in the current implementation. We used double here to match the C/C++ code.

Here's the same algorithm implemented in C:

And here's the equivalent implementation in C++:

That's it for the code listings. Let's now take a closer look at how it all works.

Just One Line Changed from Last Time!

The detailed structure of the code is nearly identical to the one from the previous article, so please refer to that for an in-depth explanation.

[ ↓ Previous Code ]


	...
	
	// Add the area of the i-th rectangle (strip) to the total
	value += f(x) * delta;
	
	...
square.txt

[ ↓ This Time's Code ]


	...
	
	// Add the area of the i-th trapezoid to the total
	value += ( f(x) + f(x+delta) ) * delta / 2.0;
	
	...
trapezoidal.txt

In other words, we simply swapped out the formula for the rectangle's area with the one for a trapezoid:
\[ \textrm{Area of i-th trapezoid} = \frac{ (\textrm{Height}_{Left} + \textrm{Height}_{Right} ) \times \textrm{Width} }{ 2 } \] \[ = \frac{ ( f(x_i) + f(x_{i+1}) ) }{ 2 } \Delta x \] \[ = \frac{ ( f(x_i) + f(x_i + \Delta x) ) }{ 2 } \Delta x \]

So, What About the Error?

Can this one-line change really reduce the error that dramatically? Let's try running the program and find out.

When you execute the program, a graph of the integration process appears. Since the integrand is currently \(f(x) = \cos x\), the integral should trace the shape of \(sin x\).

A graph of the integration process
A graph of the integration process
The red line (barely visible because it overlaps) represents the integration results from the program. The blue line is the exact function \(sin x\), plotted for comparison.

As shown above, the **red line** (our computed result) nearly overlaps the blue line, which represents the exact values of \(sin x\).

Even with just N = 10, meaning only 10 trapezoids were used for approximation, the accuracy is quite impressive.

How to overlay formulas on the graph
The VCSSL environment uses **RINEARN Graph 2D** as its default graphing tool, which allows you to overlay formulas on your data. In the graph window, go to "Tools > Math", enter sin(<x>) into the input field, then click the "PLOT" button. The graph of \(sin x\) will be drawn over your data in blue.

Now let's compare this result with the graph from the previous program that used the rectangular method (i.e., strips), focusing on the upper-right region where the deviation was most visible.

Comparison Graph (N = 10)
Comparison Graph (N = 10)
Comparison between the trapezoidal and rectangular methods (both using N = 10). The blue line is the exact value; the red line is the computed result. You can clearly see that the trapezoidal method gives a closer approximation.

Even with the same subdivision count \(N = 10\), the trapezoidal method gives a more accurate result than the rectangular method, just as we expected.

What Happens as We Increase N?

The graph gives us a good visual idea of the accuracy, but let's also look at the actual numerical values. Here's an example of the output in the console:

0.0    0.0
0.1    0.0997502082639013
0.2    0.19850374541986468
...
0.8    0.7167581945005881
0.9    0.7826740283814796
1.0    0.8407696420884198

In each line, the left column shows the x-value, and the right column shows the accumulated integral value up to that point. Each step adds the area of one trapezoid.

The final value "0.8407696420884198" gives us the total integral value of: \[ \int^{1}_{0} \cos(x) dx \] The exact value is: \[ = \sin 1 \approx 0.8414709848... \] So we start to see a small discrepancy in the third decimal place. That's our approximation error.

Now, what happens when we increase \(N\), the number of subdivisions?

N=10:       0.8407696420884198
N=100:      0.8414639725380026
N=1000:     0.8414709146853138
N=10000:    0.841470984106668
N=100000:   0.8414709848008824

As you can see, increasing \(N\) rapidly improves the result's accuracy. From this, we can observe that the trapezoidal method increases accuracy by roughly two digits every time you increase \(N\) by a factor of 10.

This is known as having second-order accuracy.

In contrast, the rectangular method we used previously only improved by one digit per tenfold increase in \(N\), making it a first-order method.

The Importance of Algorithmic Order

In numerical computation, the order of accuracy is a big deal.

Generally, higher-order methods yield better accuracy with fewer steps, reducing both error and computation time.

However, high-order methods often involve heavier calculations per step, so increasing the step count might not be practical in all cases. Also, how the errors behave -- whether they accumulate steadily or oscillate -- can affect which method is most suitable.

In serious numerical computing, these trade-offs must be considered carefully when choosing an algorithm.

Personal Note:

First-order methods like the rectangular method may not be widely used in practice due to poor accuracy and speed. But they're not without value!

Personally, I often start with a simple method like the rectangle rule when writing a new program -- it's easier to get right. Once I've verified that the basic structure works, I swap in higher-order methods. This helps catch bugs early on.

A Reasonable Step Up -- But Not the Final Destination

The trapezoidal method is a simple and approachable way to get noticeably better accuracy than the rectangle method, without making the code much more complex.

It's not a high-precision solution, but when you want a quick and lightweight approach that still gives decent results, it can be a practical choice in casual or low-demand scenarios.

After all, you're just changing one line of code from the rectangular method, and the accuracy improves significantly. That kind of "easy gain" is one of the small joys of numerical programming.

But -- is the trapezoidal method enough for serious use?
Not quite. In most real-world applications where numerical integration matters, methods with higher-order accuracy (like fourth-order) are the norm.

The good news? With just a little more effort, you can step up to that level. In the next article, we'll explore Simpson’s Rule -- a method that’s still simple, but powerful enough for more serious work.

[ Articles in the Numerical Integration Series ]

License

This VCSSL/Vnano code (files with the ".vcssl" or ".vnano" extensions) is released under the CC0 license, effectively placing it in the public domain. If any sample code in C, C++, or Java is included in this article, it is also released under the same terms. You are free to use, modify, or repurpose it as you wish.

* The distribution folder also includes the VCSSL runtime environment, so you can run the program immediately after downloading. The license for the runtime is included in the “License” folder.
(In short, it can be used freely for both commercial and non-commercial purposes, but the developers take no responsibility for any consequences arising from its use.) For details on the files and licenses included in the distribution folder, please refer to "ReadMe.txt".

* The Vnano runtime environment is also available as open-source, so you can embed it in other software if needed. For more information, see here.


Japanese English
[ Prev | Index | Next ]
Numerical Integration Using Simpson's Rule (Quadratic Approximation)

Calculates the value of a definite integral using a method that approximates the curve with parabolas, achieving even higher accuracy than the trapezoidal method.
Numerical Integration Using the Trapezoidal Method (Trapezoidal Approximation)

Calculates the value of a definite integral by summing up small trapezoids that approximate the area under the curve, offering higher accuracy than the rectangular method.
Numerical Integration Using the Rectangular Method (Rectangular Approximation)

Calculates the value of a definite integral using a simple and intuitive method that approximates the area under the curve with rectangular strips.
Tool For Converting Units of Angles: Degrees and Radians

A GUI tool for converting the angle in degrees into radians, or radians into degrees.
Fizz Buzz Program

A program printing the correct result of Fizz Buzz game.
Vnano | Output Data of Numerical Integration For Plotting Graph

Example code computing integrated values numerically, and output data for plotting the integrated functions into graphs.
Vnano | Compute Integral Value Numerically

Example code computing integral values numerically by using rectangular method, trapezoidal method, and Simpson's rule.
Index
[ Prev | Index | Next ]
Numerical Integration Using Simpson's Rule (Quadratic Approximation)

Calculates the value of a definite integral using a method that approximates the curve with parabolas, achieving even higher accuracy than the trapezoidal method.
Numerical Integration Using the Trapezoidal Method (Trapezoidal Approximation)

Calculates the value of a definite integral by summing up small trapezoids that approximate the area under the curve, offering higher accuracy than the rectangular method.
Numerical Integration Using the Rectangular Method (Rectangular Approximation)

Calculates the value of a definite integral using a simple and intuitive method that approximates the area under the curve with rectangular strips.
Tool For Converting Units of Angles: Degrees and Radians

A GUI tool for converting the angle in degrees into radians, or radians into degrees.
Fizz Buzz Program

A program printing the correct result of Fizz Buzz game.
Vnano | Output Data of Numerical Integration For Plotting Graph

Example code computing integrated values numerically, and output data for plotting the integrated functions into graphs.
Vnano | Compute Integral Value Numerically

Example code computing integral values numerically by using rectangular method, trapezoidal method, and Simpson's rule.
News From RINEARN
* VCSSL is developed by RINEARN.

English Documentation for Our Software and VCSSL Is Now Nearly Complete
2025-06-30 - We're happy to announce that the large-scale expansion of our English documentation with the support of AI — a project that began two years ago — has now reached its initial target milestone.

VCSSL 3.4.52 Released: Enhanced Integration with External Programs and More
2025-05-25 - This update introduces enhancements to the external program integration features (e.g., for running C-language executables). Several other improvements and fixes are also included. Details inside.

Released: Latest Version of VCSSL with Fixes for Behavioral Changes on Java 24
2025-04-22 - VCSSL 3.4.50 released with a fix for a subtle behavioral change in absolute path resolution on network drives, introduced in Java 24. Details inside.

Released the Latest Versions of RINEARN Graph and VCSSL - Now Supporting Customizable Tick Positions and Labels!
2024-11-24 - Starting with this update, a new "MANUAL" tick mode is now supported, allowing users to freely specify the positions and labels of ticks on the graph. We'll explain the details and how to use it.

Released Exevalator 2.2: Now Compatible with TypeScript and Usable in Web Browsers
2024-10-22 - The open-source expression evaluation library, Exevalator, has been updated to version 2.2. It now supports TypeScript and can be used for evaluating expressions directly in web browsers. Explains the details.

Behind the Scenes of Creating an Assistant AI (Part 1: Fundamental Knowledge)
2024-10-07 - The first part of a series on how to create an Assistant AI. In this article, we introduce the essential knowledge you need to grasp before building an Assistant AI. What exactly is an LLM-based AI? What is RAG? And more.

Launching an Assistant AI to Support Software Usage!
2024-09-20 - We've launched an Assistant AI that answers questions about how to use RINEARN software and helps with certain tasks. Anyone with a ChatGPT account can use it for free. We'll explain how to use it.

Software Updates: Command Expansion in RINEARN Graph, and English Support in VCSSL
2024-02-05 - We updated our apps. This updates include "Enhancing the Command-Line Features of RINEARN Graph" and "Adding English Support to VCSSL." Dives into each of them!