blab
blab

Reputation: 121

tan in javascript

tan(5.3) = 0.09276719520463

but in javascript:

Math.tan(5.3) = -1.50127339580693

how do i calculate Math.tan(something) in javascript in the deg mode?

Upvotes: 12

Views: 12746

Answers (3)

Kirk Strobeck
Kirk Strobeck

Reputation: 18589

So hard to find !

To accomplish basic triangle math in JavaScript, use ..

Math.atan(opposite/adjacent) * 180/Math.PI

Upvotes: 6

Phrogz
Phrogz

Reputation: 303224

Instead of writing a wrapper function for it (and taking a performance hit), you can multiply by these constants:

var deg2rad = Math.PI/180;
var rad2deg = 180/Math.PI;

And then use them like so:

var ratio   = Math.tan( myDegrees * deg2rad );
var degrees = Math.atan( ratio ) * rad2deg;

JavaScript deals only in radians, both as arguments and return values. It's up to you to convert them as you see fit.

Also, note that if you're trying to find the degrees of rotation for xy coordinates, you should use Math.atan2 so that JavaScript can tell which quadrant the point is in and give you the correct angle:

[ Math.atan( 1/ 1), Math.atan2( 1, 1) ]; // [  45,  45 ]
[ Math.atan( 1/-1), Math.atan2( 1,-1) ]; // [ -45, 135 ]
[ Math.atan(-1/ 1), Math.atan2(-1, 1) ]; // [ -45, -45 ]
[ Math.atan(-1/-1), Math.atan2(-1,-1) ]; // [  45,-135 ]

Upvotes: 29

Cronco
Cronco

Reputation: 589

From https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/tan

function getTanDeg(deg) {
   var rad = deg * Math.PI/180;
   return Math.tan(rad)
}

Upvotes: 11

Related Questions