Skip to content

Instantly share code, notes, and snippets.

@xtrp
Created November 26, 2020 20:21
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Maclaurin/Taylor Series Calculation of Sin and Cos in JavaScript
// round a number (x) to nearest 10 digits
const rounded = (x) => {
return parseFloat(x.toFixed(10));
}
// get the factorial of a number (x)
// factorial(x) is the product of every number from 1 to x inclusive
const factorial = (x) => {
let n = 1; // n is the result
// multiply n by every number from 1 to x inclusive
for(let i = 2; i <= x; i++) {
n *= i;
}
return n;
}
/* get the result of the cos and sin formulas
where the functions are sin(x radians) or cos(x radians),
n is the start value (x for sin, 1 for cos), and i_start
is the exponent and factorial base in the first term */
const computeSeries = (x, n, i_start) => {
const iterations = 20; // iterations is twice the amount of terms to use
let multiplier = 1;
let i = i_start;
while(i < i_start + iterations) {
multiplier *= -1; // alternates between addition and subtraction each iteration
const next_term = (x**i) / factorial(i); // each term is (x^i) / i!
n += multiplier * next_term // add or subtract from final result
i += 2 // i increases by 2 each term
}
return n
}
// get sin of x radians
const sin = (x) => {
return rounded(computeSeries(x, x, 3));
}
// get cos of x radians
const cos = (x) => {
return rounded(computeSeries(x, 1, 2));
}
// get sin of x degrees
const sinDeg = (x) => {
return sin(x * Math.PI / 180);
}
// get cos of x degrees
const cosDeg = (x) => {
return cos(x * Math.PI / 180);
}
// test the functions
console.log(sin(Math.PI / 6)); // 0.5
console.log(sinDeg(45)); // 0.7071
console.log(sinDeg(52)); // 0.78801
console.log(cos(Math.PI / 3)); // 0.5
console.log(cosDeg(45)); // 0.7071
console.log(cosDeg(52)); // 0.615661
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment