Skip to content

Instantly share code, notes, and snippets.

@jadeallenx
Last active December 18, 2015 17:09
Show Gist options
  • Save jadeallenx/5816838 to your computer and use it in GitHub Desktop.
Save jadeallenx/5816838 to your computer and use it in GitHub Desktop.
Calculate a Riemann approximation
-module(riemann).
-export([riemann/2]).
riemann(Function, Delta) when is_function(Function) andalso is_float(Delta) ->
I = fun(X) -> Function(X) * Delta end,
R = fun(X1, Acc) -> I(X1) + Acc end,
fun(A, B) -> lists:foldl(R, 0, seq_float(A, B, Delta)) end.
% https://gist.github.com/andruby/241489
seq_float(Min, Max, Inc, Counter, Acc) when (Counter*Inc + Min) >= Max ->
lists:reverse([Max|Acc]);
seq_float(Min, Max, Inc, Counter, Acc) ->
seq_float(Min, Max, Inc, Counter+1, [Inc * Counter + Min|Acc]).
seq_float(Min, Max, Inc) ->
seq_float(Min, Max, Inc, 0, []).

Given a function X, return a function that takes two points A, B and computes the approximation of the area under the curve of F(X)

1> c(riemann).                                 
{ok,riemann}
2> F = riemann:riemann(fun(X) -> 1 end, 0.1).
#Fun<riemann.2.110299938>
3> F(0, 0.9).
0.9999999999999999
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment