Maclaurin/Taylor Series Calculation of Sin and Cos in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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