473,883 Members | 1,653 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to calculate angle of a line

8,435 Recognized Expert Expert
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
19 36463
Killer42
8,435 Recognized Expert Expert
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 Recognized Expert Top Contributor
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 Recognized Expert Expert
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 Recognized Expert Expert
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 Recognized Expert Expert
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
hopalongcassidy
2 New Member
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 Recognized Expert Expert
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 New Member
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
Verrazano
1 New Member
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 Recognized Expert Expert
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
3135
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... except (for example) a = b + 10; needs to be a = b + (Angle) 10; Could some kind soul comment on my code and show me how it could be
2
7242
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 need to compute the bezier control points (start point, point A, point B, point C).
2
11239
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 line should look like?
2
7142
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 does this? I was thinking something like: Public Sub DrawLine(X1 as single, Y1 as single, Len as single, Angle as single, byref X2 as single, byref Y2 as single) and have X2 and Y2 assigned in the Sub (rather than just a line drawn - because I...
15
46497
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 particle is above or below, in front or behind the refernce particle. If I have a reference particle at (10,10), and another particle at (20,20), i'm currently finding the angle by: angle = atan((10-20)/(10-20)) = 45 degrees. When I draw this...
8
17831
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 position is from a given object and what the angle is between them. Any help please? Thanks, Gil
4
6396
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 VertCrossHairY2 As Integer = 80
6
2470
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 tangential velocity*/ real vi = sqrt(p->state.V* p->state.V + p->state.V* p->state.V + p->state.V* p->state.V);
4
7469
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 specify an input and output stream to use in place of the console. I could not
0
9934
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9789
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11137
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10409
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9570
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7120
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5795
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4608
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4214
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.