Skip to content

Instantly share code, notes, and snippets.

@joemaffei
Created November 23, 2024 01:12
Show Gist options
  • Save joemaffei/0ca82f31e5e3e68377a39fca1d881538 to your computer and use it in GitHub Desktop.
Save joemaffei/0ca82f31e5e3e68377a39fca1d881538 to your computer and use it in GitHub Desktop.
Leibniz's formula for Pi using functional programming
const identity = x => x
const withIndex = fn => (_, i) => fn(i);
const getIndex = withIndex(identity);
const positiveIntegers = (length) => Array.from({ length }).map(getIndex);
const isEven = n => n % 2 === 0;
const isOdd = n => !isEven(n);
const odd = (...numbers) => numbers.filter(isOdd);
const reciprocal = n => 1 / n;
const inverse = (...numbers) => numbers.map(reciprocal);
const add = (a, b) => a + b;
const sum = (...args) => args.reduce(add, 0);
const evenIndexed = (...args) => args.filter(withIndex(isEven));
const oddIndexed = (...args) => args.filter(withIndex(isOdd));
const alternatingSum = (...args) => sum(...evenIndexed(...args)) - sum(...oddIndexed(...args));

const MAX_INTEGER = 100000;
const pi = () => 4 * alternatingSum(...inverse(...odd(...positiveIntegers(MAX_INTEGER))));

pi();
flowchart LR
  MAX_INTEGER --> pi
  isEven --> isOdd
  
  identity --> withIndex
  withIndex --> getIndex
  getIndex --> positiveIntegers
  positiveIntegers --> pi

  withIndex --> evenIndexed
  isEven --> evenIndexed
  isOdd --> odd
  odd --> pi
  
  reciprocal --> inverse
  inverse --> pi
  
  isOdd --> oddIndexed
  withIndex --> oddIndexed
  oddIndexed --> alternatingSum
  evenIndexed --> alternatingSum
  add --> sum
  sum --> alternatingSum
  alternatingSum --> pi
Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment