Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { isArray, isString, isFunction } from "lodash";
- const { performance } = require("perf_hooks");
- type Parameters<Fn> = Fn extends (...args: infer T) => any ? T : never;
- const trampoline = <Fn extends (...args: any[]) => any>(
- fn: Fn,
- ...args: Parameters<Fn>
- ) => {
- let result = fn(...args);
- let i: number = 0;
- while (result instanceof Function) {
- result = result();
- }
- return result as ReturnType<Fn>;
- };
- const piOver4 = (precision: number) => {
- const _piOver4 = (precision: number, current = 0, iteration = 0): number => {
- const sign = iteration % 2 ? -1 : 1;
- const nextApproximation = current + sign / (1 + 2 * iteration);
- return Math.abs(current - nextApproximation) <= precision / 4
- ? (nextApproximation as any)
- : ((() => _piOver4(precision, nextApproximation, iteration + 1)) as any);
- };
- return trampoline(_piOver4, precision);
- };
- const pi = (precision: number) => 4 * piOver4(precision);
- const funcTimer = <Fn extends (...args: any[]) => any>(
- fn: Fn,
- ...args: Parameters<Fn>
- ) => {
- let result: ReturnType<Fn>;
- const start = performance.now();
- result = fn(...args);
- const end = performance.now();
- console.log({
- time: (end - start).toFixed(3) + "ms",
- result
- });
- return result;
- };
- const pi_while = (precision: number) => {
- let approximation;
- let nextApproximation = 0;
- let iteration: number = 0;
- do {
- approximation = nextApproximation;
- const sign = iteration % 2 ? -1 : 1;
- const summand = sign / (1 + 2 * iteration);
- nextApproximation = nextApproximation + summand;
- iteration++;
- } while (Math.abs(nextApproximation - approximation) > precision / 4);
- return 4 * nextApproximation;
- };
- const factorial = (n: number): number => (n === 0 ? 1 : n * factorial(n - 1));
- const e_while = (precision: number) => {
- let approximation: number;
- let nextApproximation: number = 0;
- let iteration = 0;
- do {
- approximation = nextApproximation;
- const summand = 1 / factorial(iteration);
- nextApproximation += summand;
- iteration++;
- } while (Math.abs(nextApproximation - approximation) > precision);
- return nextApproximation;
- };
- const timedPi = (precision: number) => funcTimer(pi, precision);
- const timedPi_while = (precision: number) => funcTimer(pi_while, precision);
- const timedE_while = (precision: number) => funcTimer(e_while, precision);
- [
- 0.1,
- 0.01,
- 0.001,
- 0.0001,
- 0.00001,
- 0.000001,
- 0.0000001,
- 0.00000001,
- 0.000000001,
- 0.0000000001,
- 0.00000000001,
- 0.000000000001,
- 0.0000000000001,
- 0.00000000000001,
- 0.000000000000001,
- 0.0000000000000001,
- 0.00000000000000001
- ].forEach(timedE_while);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement