473,394 Members | 1,759 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

How to calculate angle of a line

8,435 Expert 8TB
Hi all.

Sorry to be brief, but have to leave.

If I have the coordinates of two points (on the computer screen), how do I calculate the angle of the line which joins them?

I know, my terms are vague and in some cases completely wrong (for instance it would be an "interval", not a line) but hopefully you get the idea.
Oct 17 '07 #1

✓ answered by Killer42

Actually, here's a shorter (and probably very slightly faster) version...
Expand|Select|Wrap|Line Numbers
  1. Option Explicit
  2. DefLng A-Z
  3.  
  4. Private DistanceX As Single, DistanceY As Single
  5. Private Const NotQuiteZero As Single = 0.00001
  6. Private Const Ninety As Long = 90
  7. Private Const TwoSeventy As Long = 270
  8. Private Const RadsToDegs As Single = 57.29578
  9.  
  10.  
  11. Public Function DirectionOfLine2(ByVal From_X As Single, ByVal From_Y As Single, ByVal To_X As Single, ByVal To_Y As Single) As Single
  12.   ' Given two points, return the angle of the line from P1 to P2.
  13.   If From_Y = To_Y Then To_Y = From_Y - NotQuiteZero ' Prevent div-by-zero error.
  14.   If To_Y < From_Y Then
  15.     DirectionOfLine2 = Ninety + Atn((To_X - From_X) / (To_Y - From_Y)) * RadsToDegs
  16.   Else
  17.     DirectionOfLine2 = TwoSeventy + Atn((To_X - From_X) / (To_Y - From_Y)) * RadsToDegs
  18.   End If
  19. End Function

19 36348
Shashi Sadasivan
1,435 Expert 1GB
Trignometry :)
you know the cordinates of the points,
Get the height and the width of the that line and use tan

angle = tan inverse ( X / Y)
Attached Images
File Type: jpg tan.jpg (5.4 KB, 7476 views)
Oct 17 '07 #2
Killer42
8,435 Expert 8TB
Trignometry :)
you know the cordinates of the points,
Get the height and the width of the that line and use tan

angle = tan inverse ( X / Y)
Thanks. Haven't done a lot of trig for a few years.

I had already worked out the horizontal and vertical distance (X and Y), and I routinely use these to calculate the straight-line distance (good old Pythagorus), but didn't know how to work out the angle.

I'm still not sure. I need to be able to go the full circle. That is, angles all the way around to 360 degrees (or just under, since that would be the same as zero of course). Will this work? Not sure what you mean by "inverse", in this context. (Be gentle, it has been a long time...)
Oct 17 '07 #3
Shashi Sadasivan
1,435 Expert 1GB
I'm still not sure. I need to be able to go the full circle. That is, angles all the way around to 360 degrees (or just under, since that would be the same as zero of course). Will this work?
Depends on your frame of reference (my frame of reference is the x axis)

Not sure what you mean by "inverse", in this context. (Be gentle, it has been a long time...)
Well... lets assume that we now see @ as theta (the general angle variable)
tan @ = X/Y;
so @ = tan inverse (X/Y)
i have to type in inverse, because i cant type in -1 in superscript :D

Hope the math comes along well for you :D

cheers
Oct 17 '07 #4
bartonc
6,596 Expert 4TB
Hi all.

Sorry to be brief, but have to leave.

If I have the coordinates of two points (on the computer screen), how do I calculate the angle of the line which joins them?

I know, my terms are vague and in some cases completely wrong (for instance it would be an "interval", not a line) but hopefully you get the idea.
Here's how I'd do it:
Expand|Select|Wrap|Line Numbers
  1. >>> from math import atan, degrees
  2. >>> bottom, left = 0, 0
  3. >>> top, right = 10.0, 20.0
  4. >>> degs = degrees(atan((top - bottom)/(right - left)))
  5. >>> print degs
  6. 26.5650511771
  7. >>> 
Oct 17 '07 #5
Shashi Sadasivan
1,435 Expert 1GB
Expand|Select|Wrap|Line Numbers
  1. Double radians = Math.Atan((x2-x1)/(y2-y1));
  2. Double degrees = radians *  180 / Math.PI;
Thats c# :D
Oct 18 '07 #6
Killer42
8,435 Expert 8TB
Thanks for that, people.

Since I need to cover the full circle (in other words, the angle could be up to 360 degrees), I've had to do some real kludges. Hope someone can point out a better way.
  • Calculate (absolute) DistanceX & DistanceY
  • Calculate Ratio: DistanceX / DistanceY
  • Calculate Degrees = Atn(Ratio) * RadsToDegs
    This provides a value between 0 and 90, which is not good enough. So...
  • Determine which "quadrant" we're in (lower-right = 0, upper-right = 1, upper left = 2, lower left = 3) by checking signs of horizontal & vertical distances.
  • Adjust the angle based on the quadrant.
    • Quadrant 0: 360 - Degrees
    • Quadrant 1: 90 - Degrees
    • Quadrant 2: 90 + Degrees
    • Quadrant 3: 270 - Degrees
  • And that's it. Simple, huh. :)
This does produce what looks like the right answer, or close enough. But as you can see, it's rather messy so far.

Note, using the absolute values of the distances dates back to before you people provided the Atan solution, so I'll be revisitng that to see what I can do better.
Oct 18 '07 #7
Shashi Sadasivan
1,435 Expert 1GB
Well...I would say calculate the degrees,
the values of X=(x2-x1) and Y=(y2-y1) will indicate which quadrant the angle is being measured to.


Assume that the quadrants are being split as in picture.
X(sign)__Y(sign) ___ Quadrant
__+_______+________ 0
__+_______- ________1
__-_______-_________2
__-_______+_________3

(Excuse the undescores, as that gets trimmed off in the posts)

The angle is measured always to the X axis, so then apply the required arithmetic to get the desired angle from your frame of ref, and angle of ref (ie, whether clockwise or anti-clockwise).
Attached Images
File Type: jpg quadrants.jpg (2.6 KB, 1278 views)
Oct 18 '07 #8
Killer42
8,435 Expert 8TB
Thanks Shashi. That's pretty much what I'm doing. I've just complicated it a little by using the absolute values of X and Y to begin with. I plan to change that.
Oct 18 '07 #9
Shashi Sadasivan
1,435 Expert 1GB
I would suggest to keep the values of X and Y as they are.
the angles yould come as positive or negative depending which quadrant there are in (0 and 2 will be positive and 1,3 negative)

Soall you then need to find which qadrant they are in
and then
(90 * (quadrant number +1)) + angle = resulting required angle

the resulting angle starts from the X axis at quadrant 0, and works it was anti clock wise from there.

cheers :) (woo hoo,, i never knew i could start liking trignometry....no...wait, i started avoiding it when my games designer friend came to ask me doubts :P)
Oct 18 '07 #10
Killer42
8,435 Expert 8TB
Ok, thanks for that.

One thing, though. This is something which keeps cropping up here lately. The word is "questions", not "doubts".
Oct 18 '07 #11
Shashi Sadasivan
1,435 Expert 1GB
Oh, no it was doubts,
Because he was good at geometry and trignometry, and he would come and pile everything up on me, and explaining the humungus geometry, seemed that he would almost recreate the entire earth in detail.
And expected me to follow him, and call out when the error is occouring !!

so doubts...not questions !!! (questions would have been easier than doubts)
Oct 18 '07 #12
bartonc
6,596 Expert 4TB
Thanks for that, people.

Since I need to cover the full circle (in other words, the angle could be up to 360 degrees), I've had to do some real kludges. Hope someone can point out a better way.
  • Calculate (absolute) DistanceX & DistanceY
  • Calculate Ratio: DistanceX / DistanceY
  • Calculate Degrees = Atn(Ratio) * RadsToDegs
    This provides a value between 0 and 90, which is not good enough. So...
  • Determine which "quadrant" we're in (lower-right = 0, upper-right = 1, upper left = 2, lower left = 3) by checking signs of horizontal & vertical distances.
  • Adjust the angle based on the quadrant.
    • Quadrant 0: 360 - Degrees
    • Quadrant 1: 90 - Degrees
    • Quadrant 2: 90 + Degrees
    • Quadrant 3: 270 - Degrees
  • And that's it. Simple, huh. :)
This does produce what looks like the right answer, or close enough. But as you can see, it's rather messy so far.

Note, using the absolute values of the distances dates back to before you people provided the Atan solution, so I'll be revisitng that to see what I can do better.
I developed these for my Garmin GPS interface:
Expand|Select|Wrap|Line Numbers
  1.  
  2. def QuadHeading(east, north):
  3.     """Given the vector, convert to degrees in a quadrant.
  4.        N is zero, S is 180, E is positive, W is negitive."""
  5.     return degrees(atan2(east, north))
  6.  
  7. def QuadToCirc(heading):
  8.     """Convert quadrant to degrees of a circle."""
  9.     return (heading, abs(heading + 360))[heading < 0] # index the list on bool
Oct 18 '07 #13
Killer42
8,435 Expert 8TB
For future reference, here's the function I ended up putting together in VB6. You'll note that I've defined named constants for everything rather than hard-coding any values. This is based on the fact that constants have traditionally been faster to reference than variables. I don't actually know whether this is still the case in VB6.

Expand|Select|Wrap|Line Numbers
  1. Option Explicit
  2. DefLng A-Z
  3.  
  4. Private DistanceX As Single, DistanceY As Single
  5. Private Const Zero As Long = 0
  6. Private Const NotQuiteZero As Single = 0.00001
  7. 'Private Const One As Long = 1
  8. 'Private Const Two As Long = 2
  9. 'Private Const Three As Long = 3
  10. Private Const Ninety As Long = 90
  11. Private Const TwoSeventy As Long = 270
  12. Private Const Pi As Single = 3.14159265358979
  13. Private Const RadsToDegs As Single = 180 / Pi
  14.  
  15. Public Function DirectionOfLine(ByVal From_X As Single, ByVal From_Y As Single, ByVal To_X As Single, ByVal To_Y As Single) As Single
  16.   ' Given two points, return the angle of the line from P1 to P2.
  17.   DistanceX = To_X - From_X
  18.   DistanceY = To_Y - From_Y
  19.   If DistanceY = Zero Then DistanceY = NotQuiteZero ' Prevent div-by-zero error.
  20.   If DistanceY < Zero Then
  21.     DirectionOfLine = Ninety + Atn(DistanceX / DistanceY) * RadsToDegs
  22.   Else
  23.     DirectionOfLine = TwoSeventy + Atn(DistanceX / DistanceY) * RadsToDegs
  24.   End If
  25. End Function
Oct 19 '07 #14
Killer42
8,435 Expert 8TB
Actually, here's a shorter (and probably very slightly faster) version...
Expand|Select|Wrap|Line Numbers
  1. Option Explicit
  2. DefLng A-Z
  3.  
  4. Private DistanceX As Single, DistanceY As Single
  5. Private Const NotQuiteZero As Single = 0.00001
  6. Private Const Ninety As Long = 90
  7. Private Const TwoSeventy As Long = 270
  8. Private Const RadsToDegs As Single = 57.29578
  9.  
  10.  
  11. Public Function DirectionOfLine2(ByVal From_X As Single, ByVal From_Y As Single, ByVal To_X As Single, ByVal To_Y As Single) As Single
  12.   ' Given two points, return the angle of the line from P1 to P2.
  13.   If From_Y = To_Y Then To_Y = From_Y - NotQuiteZero ' Prevent div-by-zero error.
  14.   If To_Y < From_Y Then
  15.     DirectionOfLine2 = Ninety + Atn((To_X - From_X) / (To_Y - From_Y)) * RadsToDegs
  16.   Else
  17.     DirectionOfLine2 = TwoSeventy + Atn((To_X - From_X) / (To_Y - From_Y)) * RadsToDegs
  18.   End If
  19. End Function
Oct 19 '07 #15
Hi all.

Sorry to be brief, but have to leave.

If I have the coordinates of two points (on the computer screen), how do I calculate the angle of the line which joins them?

I know, my terms are vague and in some cases completely wrong (for instance it would be an "interval", not a line) but hopefully you get the idea.

Try arctan((y2-y1)/(x2-x1))

By the way, I read all of the replies and every one of them is wrong. The tangent of an angle is the change in Y divided by the change in X. The change in X divided by the change in Y is the cotangent!!!
Oct 19 '07 #16
Killer42
8,435 Expert 8TB
Try arctan((y2-y1)/(x2-x1))
Um... isn't that what I've got?

By the way, I read all of the replies and every one of them is wrong. The tangent of an angle is the change in Y divided by the change in X. The change in X divided by the change in Y is the cotangent!!!
Thanks for the correction. I have to admit though, all I'm really concerned about is whether the code works. Which it does.
Oct 20 '07 #17
cowpie
1
Since this is the first link that pops up on Google when I search how to do this, I thought I'd include a much easier method.

Expand|Select|Wrap|Line Numbers
  1. Double radians = Math.Atan2((y2-y1), (x2-x1));
  2. Double degrees = radians * 180 / Math.PI;
  3.  
  4. if(degrees < 0) {
  5.    degrees += 360; // degrees are now 0-360
  6. }
Aug 20 '11 #18
recently today my friend and I worked this out originally I thought of using the four quadrants of a graph to get the angle, but the way I had done it ended with me having to build a large table to get values back.
so after about an hour we came up with this:
cos^-1(adjacent/hypotenuse) this translates to being: let one point be your origin and the other point be the x and y values you get the hypotenuse by obviously using the Pythagorean theorem. So lets say the coordinates are (0,0) and (4,4) using the formula above it would look like this.
cos^-1(4/sqrt(4^2+4^2)) = 45 degrees which is correct since the slope of the line is 1/1.
hope this helps,
Verrazano
Nov 22 '11 #19
Killer42
8,435 Expert 8TB
Cowpie, what language is that? VB.Net?

I am/was working in VB6. By the way, this question is from 4 years ago. :-)
Dec 13 '11 #20

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Darren Grant | last post by:
Hi there, I've attempted to implement an Angle class. An Angle is a subset of an integer, where the range is [0,360). All other operations should be permitted. The code works, I think......
2
by: Dennis Myrén | last post by:
Hi. Sorry if this post might be a little off the topic, but just in case anyone knows... Given a size, a position, a start angle and a sweep angle, i want to draw a bezier curve. I will...
2
by: Joe | last post by:
I need to add a trend line to a scatter plot (not automatically supported by the charting package) but I don't know how to calculate it. Is there any formulas around for calculating what the trend...
2
by: The Mess | last post by:
I am using VB5. I wish I had a function to draw a line, giving the angle and length but I do not have the math skills involved to do this. Does anyone have a function that they care to share that...
15
by: cwsullivan | last post by:
Hi gang, I have a grid full of particles in my program, and I want to find an angle between two particles. I'm having trouble because it seems like the answer depends on whether or not the target...
8
by: giloosh | last post by:
how would i get the distance and angle between 2 points on the screen. For example: what is the distance between (100,50) and (250,70) what i really wanna do is see how far the current mouse...
4
by: Jem | last post by:
Hi all I have the following code which draws a vertical line on a form... Dim VertCrossHairX1 As Integer = 75 Dim VertCrossHairX2 As Integer = 75 Dim VertCrossHairY1 As Integer = 70 Dim...
6
by: royrana | last post by:
Hello, I am working on a problem in which a particle hits a wall and gets reflected. I need to calculate the tangential velocity and the impact angle with the wall. I wrote this: /*for...
4
by: Keith Hughitt | last post by:
Hi all, I am using someone else's script which expects input in the form of: ./script.py <arg1arg2 I was wondering if the angle-brackets here have a special meaning? It seems like they...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.