Skip to content

Instantly share code, notes, and snippets.

@joaofnds
Created September 25, 2018 09:38
Show Gist options
  • Select an option

  • Save joaofnds/929226d62f9ff0647179f40803dc63b4 to your computer and use it in GitHub Desktop.

Select an option

Save joaofnds/929226d62f9ff0647179f40803dc63b4 to your computer and use it in GitHub Desktop.
Functional Riemann Sums
const leftRiemannSum = (f, start, stop, inc) => {
if (start >= stop) return 0;
return f(start) * inc + leftRiemannSum(f, start + inc, stop, inc);
};
const middleRiemannSum = (f, start, stop, inc) => {
const middle = (start + inc) / 2;
if (start >= stop) return inc * f(middle);
return f(middle) * inc + middleRiemannSum(f, start + inc, stop, inc);
};
const rightRiemannSum = (f, start, stop, inc) => {
if (start >= stop) return f(stop) * inc;
return f(stop) * inc + rightRiemannSum(f, start + inc, stop, inc);
};
const expression = n => 1 / (7 - n)
console.log("left ", leftRiemannSum(expression, 2, 5, 1));
console.log("middle", middleRiemannSum(expression, 2, 5, 1));
console.log("right ", rightRiemannSum(expression, 2, 5, 1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment