The simplest, really. Probably not very Scala-ish, but it's a start.
Given a continuous function in one variable and lower and upper bounds, calculate the area under the curve by Monte Carlo integration.
All of this is hard coded, because it's an exercise in numerical methods rather than non-standard evaluation or processing user input.
... kind of.
Start with the defintion of the (arithmetic) mean of a function over a given interval:
Now define the same thing in the continuous case rather than the discrete:
Now, we can rearrange this expression to get a definition of the integral in terms of the mean and the width of the interval:
So, this implies that we can calculate the integral of
over the interval
by first getting the average of the function over the interval
, and then multiplying by
.
This is great, because very often we find ourselves in the situation
where evaluating
is easy for any given
, but integrating
over any given integral is very difficult indeed.
The simplest, most naive, approach is to Uniformly sample from the interval , and then evaluate
for each
.
Now we have a sequence
We can take the mean of this sequence, multiply by the width of the interval, and we get our discrete approximation of the integral:
I used Darren Wilkinson's
Giter8 template to get started. It gives you the Breeze
package and a main
function.
This is all I need, and is much handier than having to
write a build.sbt
file myself.
sbt new darrenjw/breeze.g8
Run with SBT
sbt run
Redefine the function f
inside the Main
object,
and you're good to go with your own continuous function in one variable.
Extending this to accepting user-inputted functions is left as an
exercise to the reader.
Please do tell me if you achieve this, because I haven't tried yet.
That's a pretty big ask. Ultimately it leads to things like Markov Chain Monte Carlo, via things like Importance Sampling.
Alternatively, there are sophisticated non-stochastic numerical integration methods like Simpson's Rule or Gaussian Quadrature.