Skip to content

Instantly share code, notes, and snippets.

@getDanArias
Created October 15, 2017 05:12
Show Gist options
  • Save getDanArias/a838f517da7b09f104f99e9ebe42c8d2 to your computer and use it in GitHub Desktop.
Save getDanArias/a838f517da7b09f104f99e9ebe42c8d2 to your computer and use it in GitHub Desktop.
Using Taylor Series to calculate Trig Functions in JavaScript
"use strict";
const power = (x, exp) => (exp < 1) ? 1 : x * power(x, exp - 1);
const factorial = x => (x < 1) ? 1 : x * factorial(x - 1);
const seriesTerm = (x, exp) => power(x, exp) / factorial(exp);
const zeroExpander = zeroes => zeroes < 0 ? 1 : 10 * zeroExpander(zeroes - 1);
const accuracyLimit = (seriesTerm, decimalPlaces) =>
seriesTerm < (decimalPlaces / zeroExpander(decimalPlaces + 1));
const seriesHelper = (x, exp, add, term = seriesTerm(x, exp)) =>
(accuracyLimit(term, 5)) ?
0 :
add ?
term + seriesHelper(x, exp + 2, !add) :
(term * -1) + seriesHelper(x, exp + 2, !add);
const sin = x => x + seriesHelper(x, 3, false);
const cos = x => 1 + seriesHelper(x, 2, false);
const tan = x => sin(x) / cos(x);
const cot = x => 1 / tan(x);
const calc = (fn, num) => console.log(`${fn.name}(${num}) = ${fn(num).toFixed(6)}`);
const num = 0.9;
calc(sin, num);
calc(cos, num);
calc(tan, num);
calc(cot, num);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment