Numeric Integration

Single Variable Integration


Integration is essentially about calculating areas. Consider the following graph.
copy
We would like to calculate the area underneath the chart, in this case, it is the blue area. The theory of integration essentially proceeds by sectioning the area underneath the chart into recangular areas, each area we know how to calculate.
copy

Implementation


We can use the davinci api to approximate the integral. Consider the following code, which utilizes the $from api.

let mesh = $from(0,1,100);

let f = Math.sin;
let integral = 0;
$from(0,2*Math.PI, 100).forEach(left=>{
    let right = left + 2*Math.PI/100;
	integral += (right - left) * f(left + (right-left)/2);					
})
					
Try it!

The davinci library also hosts an library for integration, which lets you numerically calculate these integrals without having to understand the internals.


let it = await import('/lib/numeric/integration/v1.0.0/integration.mjs');
let f = Math.sin;
let integral1 = it.leftPoint(f,{
  lower:0,
  upper: 2*Math.PI,
  numberMeshPoints:1000
});
						 
Try it!

Single Variable Integration - Monte Carlo


It is well known that monte carlo simulations can be used to calculate integrals
{% \mathbb{E}(g(x)) = \int_{a}^{b} g(x)f(x)dx %}
when f(x) is taken to be uniform over the interval [a,b]
{% \mathbb{E}(g(x)) = \int_{a}^{b} g(x)/(b-a)dx = \frac{1}{b-a} \int_{a}^{b} g(x)dx %}
{%\int_{a}^{b} g(x)dx = (b-a) \times \mathbb{E}(g(x)) %}
The following example demonstrates calculating the area of a circle with radius 1 (and hence caculating PI).


let mt = await import('/lib/numeric/integration/v1.0.0/monte-carlo.mjs');

let integral = mt.integral({
  iterations:10000,
  ranges:[[-1,1],[-1,1]],
  accept:function(x, y){
    return x*x + y*y <= 1;
  }
})
						 
Try it!

Contents