Trapezoidal rule: Numerical Methods
Tags: numericalmethods, trapezoidal, scala, functional
Published: 2018-05-20 07:12:08

 ---
title: Trapezoidal rule: Numerical Methods
published: true
description: Implementation of the trapezoidal rule in Scala
tags: NumericalMethods,Trapezoidal,Scala,Functional
---
#Introduction:
The numerical methods, is a tool that use algebraic and arithmetic techniques, to solve in an approximate way systems of complex equations. There are equations that are very difficult to solve analytically, so it is possible to reformulate these with arithmetic operations to give an approximate solution to them.There are many applications of numerical methods, we can solve integrals, derivatives, approximations.In integrals, there are several algorithms, to give an approximate solution to these, in this case we will make an implementation of the trapezoidal rule in scala.In mathematics, the trapezoid rule is a numerical integration method, that is, a method to calculate approximately the value of the definite integral.

#Trapezoidal Rule:

In mathematics, the trapezoid rule is a numerical integration method, that is, a method to calculate approximately the value of the definite integral.
![i2](http://res.cloudinary.com/dzbxcbntl/image/upload/v1526755300/Selection_004.png)
The rule is based on approximating the value of the integral of f (x) by that of the linear function that passes through the points (a, f (a)) and (b, f (b)). The integral of this is equal to the area of the trapezoid under the graph of the linear function. It follows that:
![i3](http://res.cloudinary.com/dzbxcbntl/image/upload/v1526755300/Selection_005.png)

The error is:
![i4](http://res.cloudinary.com/dzbxcbntl/image/upload/v1526755300/Selection_006.png)

Xi being a number between a and b.

![i1](https://upload.wikimedia.org/wikipedia/commons/d/dd/Trapezoidal_rule_illustration.png)

#Implementation
The implementation of the trapezoid rule was made in Scala and you can find the full implementation [here](https://github.com/jbagur/IntegrateScala/blob/master/src/Main/Integral.scala).

###Function to integrate
First we create the function that we are going to integrate, in this case we will do it with the function sin:

```scala
  //Fuction SIN
  def function(x:Double) = Math.sin(x)
```

###Trapezoidal Rule implementation
Function with 3 parameters: initial boundary value, final boundary value and length of interval:
```scala
  //Trapezoid Method
  def IntegralT(a:Double, b:Double, n:Int)={
```
Calculate number of strips, n = (final boundary value –final boundary value)/length of interval. This will use it to ecalculate the approximation in each iteration:

```scala
   var interval = ((b-a)/n)
```
set xi & xin:

```scala
    var xi = a
    var xin = b
```
Calculate Newton's interpolation formula for x0 = y x1 = b, and set initial value of the sum:

```scala
    var left = (interval)/(2.0)*(function(xi)+function(xin))
    var sum = 0.0
```
Perform following operation in loop 
sum equals: sum + f(xi)
Recalculate xi: xi+interval

```scala
    for( i <- 2 to n){
      sum += function(xi)
      xi = xi + interval
      }
```

finally we return the sum of the number of stripes, Newton's interpolation formula and the summation:

```scala
    left + interval * sum
```
to execute, we only call the function, with the established parameters, and print the result:
```scala
  def main(args: Array[String]): Unit = {
  println("Trapezoidal integration") 
  //set integrate limits, and n of iterations
  var integral = IntegralT(0,math.Pi,20)
  println("Result: "+integral)
  }
```
we execute the program with different n's: 10,20,100 to prove that, more trapezoids you use, then the integral will be more exact
```
Result: 1.8864429855731812
Result: 1.971313304401783
Result: 1.9988487057878095
```
Full code:
```scala
package Main

object Main {
  def main(args: Array[String]): Unit = {
  println("Trapezoidal integration") 
  //set integrate limits, and n of iterations
  var integral = IntegralT(0,math.Pi,20)
  println("Result: "+integral)
  }
  //Fuction SIN
  def function(x:Double) = Math.sin(x)
  
  //Trapezoid Method
  def IntegralT(a:Double, b:Double, n:Int)={
    var interval = ((b-a)/n)
    var xi = a
    var xin = b
    var left = (interval)/(2.0)*(function(xi)+function(xin))
    var sum = 0.0
    for( i <- 2 to n){
      sum += function(xi)
      xi = xi + interval
      }
    left + interval * sum
  }

}
```
#Applications
The integrals have many applications in real life, from measuring the volume of a container, and different applications in speed. Another use of integrals is for economic studies. 
##Economic surplus
![i5](https://upload.wikimedia.org/wikipedia/commons/d/d7/Economic-surpluses.svg)
The consumer surplus is the difference between the total utility that we obtain from a good or service and its market price.

The surplus of the consumer arises from the law of diminishing returns. This means that the first unit to acquire is highly valued, but as we acquire additional units, our valuation falls. However, the price we pay for any unit is always the same: the market price. In this way, we enjoy a positive surplus of the first units that we acquired until we reach the last one in which the surplus will be zero.

In graphic terms, the consumer surplus is measured as the area below the market demand curve and above the price line. The demand curve measures the amount consumers are willing to pay for each unit consumed. Then, the total area below the demand curve reflects the total utility of the consumption of the good or service. If the price paid for each unit is subtracted from this area, the surplus of the consumer is obtained.

The other part that goes from the surplus of the consumer to the supply curve is known as surplus of the producer.

###Consumers Surplus

It represents the total gain of consumers who are willing to pay more than the equilibrium price and is abbreviated EC.
![i6](http://res.cloudinary.com/dzbxcbntl/image/upload/v1526762212/Screenshot_from_2018-05-19_14-35-05.png)
For more information about this application you can follow the [link](https://en.wikipedia.org/wiki/Economic_surplus) below.

#Bibliography:
https://www.intmath.com/integration/5-trapezoidal-rule.php
http://www.mathwords.com/t/trapezoid_rule.htm
https://en.wikipedia.org/wiki/Trapezoidal_rule
http://math.slu.edu/~may/ExcelCalculus/sec-7-8-BusinessApplicationsIntegral.html