Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 961
blab Avatar asked Jan 17 '11 16:01

blab


2 Answers

So hard to find !

To accomplish basic triangle math in JavaScript, use ..

Math.atan(opposite/adjacent) * 180/Math.PI
like image 188
Kirk Strobeck Avatar answered Nov 03 '22 01:11

Kirk Strobeck


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 ]
like image 33
Phrogz Avatar answered Nov 02 '22 23:11

Phrogz