Skip to content

Instantly share code, notes, and snippets.

@declann
Last active March 5, 2024 11:25
Show Gist options
  • Save declann/eabc81b36f18acc47dd5882ea903229c to your computer and use it in GitHub Desktop.
Save declann/eabc81b36f18acc47dd5882ea903229c to your computer and use it in GitHub Desktop.
// this is https://github.com/declann/calculang-miscellaneous-models/blob/main/models/pi/nilakantha-series_esm/cul_scope_0.mjs
// but with changes described
// so that it runs on numcalc.com (QuickJS)
// with arbirary \digits settings (e.g. \digits 100)
// Ensure in numeric (not algebraic mode)
// CHANGES:
// replaced res = 0 with res=0.0 and 4 by 4.0
//pi_approximation({terms_in:2000000})-PI
//3.124999999999023437500000744628906248943328857424284029006949952945113219201746
//976010479341036799123e-20
// ^ an improvement! Though using BigNumber.js implementation I can match it too
// (vs. https://github.com/tc39/proposal-decimal which may lead to dramatic optimisation)
// note: I use loops below, which is bad in calculang (less reason-able, and will break assumptions used in tools to show workings etc)
const term_number = ({ term_number_in }) => term_number_in;
const terms = ({ terms_in }) => terms_in;
const sign = ({ term_number_in }) => Math.pow(-1, term_number({ term_number_in }) - 1); // +, -, +, -, ...
const denominator = ({ term_number_in }) => term_number({ term_number_in }) * 2 * (term_number({ term_number_in }) * 2 + 1) * (term_number({ term_number_in }) * 2 + 2);
const term = ({ term_number_in }) => sign({ term_number_in }) * (1 / denominator({ term_number_in }));
/*export const sum_of_terms = () => range(1, terms() + 1).reduce(
(acc, term_number_in) => acc + term({ term_number_in }),
0);*/
const sum_of_terms = ({ terms_in }) => {
let res = 0.0,term_number_in = 1;
while (term_number_in < terms({ terms_in })) {
res += term({ term_number_in });
term_number_in++;
}
return res;
};
const pi_approximation = ({ terms_in }) => sum_of_terms({ terms_in }) * 4.0 + 3;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment