views:

136

answers:

4

Hey guys,

I've got a line (x1,y1) and (x2,y2). I'd like to use tan inverse to find the angle of that line, how would I do so in java?

I'd like to see what angle the line makes in relation to x1,y1

+2  A: 

You need

Math.toDegrees(Math.atan((y2-y1)/(x2-x1)))

Do notice exception when x1=x2.

Gedrox
Use atan2 and you can avoid that.
Alex Feinman
Why would this be returning a negative angle?
Ulkmun
Because atan returns value between (-Pi/2, Pi/2). Use Math.atan2(). Seems it handles problems of Math.atan usage. If you need positive value, just add 2*Pi if negative value is received.
Gedrox
+4  A: 

This post Angle between 2 points has an example using atan().

stacker
+9  A: 

Use the Math.atan2 function. It is like arctan but knows about x and y coordinates, so it can handles lines that are horizontal, vertical, or pointing in other directions -- arctan's range of -pi/2 through pi/2 will not give the correct answer for some lines.

jleedev
+8  A: 

The atan2 function helps solve this problem while avoiding boundary conditions such as division by zero.

Math.atan2(y2-y1, x2-x1)
ggg