javascriptmathtrigonometry

Calculate the value of an angle in JavaScript


Im trying to make a code that calculates the value of an angle in a right angle triangle provided its sin, cos or tan. For example, in a calculator, if you have the value of sin(x) and you want to find the angle you input sin^-1(x) and get said angle. How can I make this code in JavaScript?

I tried using this code but it didnt work and I dont know if it helps me in my project:

radianToDegree = r => r * 180 * Math.PI ** -1
console.log(radianToDegree(Math.asin(0.5)).toFixed(3) * 1)


Solution

  • To calculate the angle of a right triangle when given its sine, cosine, or tangent value in JavaScript, you can use the inverse trigonometric functions (Math.asin(), Math.acos(), Math.atan()). These functions return the angle in radians, but you can easily convert it to degrees by multiplying the result by (180 / Math.PI).

    Here is an example of how you can do this:

    function calculateAngle(value, ratioType) {
        let angleInRadians;
    
        // Determine which inverse trig function to use
        if (ratioType === "sin") {
            angleInRadians = Math.asin(value);
        } else if (ratioType === "cos") {
            angleInRadians = Math.acos(value);
        } else if (ratioType === "tan") {
            angleInRadians = Math.atan(value);
        } else {
            throw new Error("Invalid ratio type. Use 'sin', 'cos', or 'tan'.");
        }
    
        // Convert radians to degrees
        const angleInDegrees = angleInRadians * (180 / Math.PI);
    
        return angleInDegrees;
    }
    
    // Examples:
    console.log(calculateAngle(0.5, "sin")); // Output: 30
    console.log(calculateAngle(0.5, "cos")); // Output: 60
    console.log(calculateAngle(1, "tan"));   // Output: 45