sin(𝑥) = 𝑥 − 𝑥 3 3! + 𝑥 5 5! − ⋯ (−1) 𝑛 𝑥 2𝑛+1 (2𝑛 + 1)! in javascript

index.tsx
function calculateSin(x, n) {
    let result = 0;
    for(let i = 0; i <= n; i++) {
        result += Math.pow(-1, i) * Math.pow(x, 2*i + 1) / factorial(2*i + 1);
    }
    return result;
}

function factorial(num) {
    if(num === 0 || num === 1) {
        return 1;
    } else {
        return num * factorial(num - 1);
    }
}

// Example usage
let x = Math.PI/4;
let n = 5;
let sinValue = calculateSin(x, n);
console.log(sinValue);
436 chars
22 lines

This code defines a function calculateSin that calculates the value of sin(x) using the given formula up to n iterations. It also includes a utility function factorial to calculate factorials. The example calculates sin(π/4) using 5 iterations.

related categories

gistlibby LogSnag