Skip to content

Instantly share code, notes, and snippets.

@carlosrberto
Created March 25, 2018 22:17
Show Gist options
  • Save carlosrberto/a84cc41c8102573a047f01949eb1a6a1 to your computer and use it in GitHub Desktop.
Save carlosrberto/a84cc41c8102573a047f01949eb1a6a1 to your computer and use it in GitHub Desktop.
Pi Calculation With JavaScript
// low perf
const fn = n => Math.pow(-1, n)/(2*n + 1);
const sum = (a, b) => a + b;
const range = (n) => {
let i = 0;
let numbers = [];
while(i < n) {
numbers.push(i);
i++;
};
return numbers;
}
const pi = 4 * range(10000).map(fn).reduce(sum);
// medium perf
const piRange = (n) => {
let i = 0;
let numbers = [];
while(i < n) {
numbers.push(fn(i));
i++;
};
return numbers;
}
const pi = 4 * piRange(10000000).reduce(sum);
// good perf
const piSum = (n, i, a) => {
let i = 0;
let sum = 0;
while(i < n) {
sum += fn(i)
i++;
};
return sum;
}
const piSumR = (n, i=0, a=0) => {
if(i === n) {
return a;
}
return piSum(n, i+1, a+fn(i));
}
const pi = 4 * piSum(20);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment