|
-
Dec 1st, 2010, 08:31 AM
#1
Thread Starter
New Member
[RESOLVED] VB Math.Atan2 not providing proper answer.. HELP!
EDIT: For anyone suffering the same problem, I found my own solution. Excel's ATAN2 function uses ATAN2(x,y) while VB uses Math.Atan2(y,x). As soon as I switched those around in my VB code it worked like a charm.
I am computing the distance and bearing between two geographic coordinates. The forumula in excel produces the correct distance (km) and bearing.
This is the formula in the bearing cell
=ATAN2(COS(lat1)*SIN(lat2)-SIN(lat1)*COS(lat2)*COS(lon2-lon1),SIN(lon2-lon1)*COS(lat2))
This is my VB code attempting to do the same thing:
Code:
Private Sub dstbrng(ByVal Lat1 As Single, ByVal Lon1 As Single, ByVal Lat2 As Single, ByVal Lon2 As Single)
Dim Lat1rad As Double
Dim Lon1rad As Double
Dim Lat2rad As Double
Dim Lon2rad As Double
Dim distrad As Double
Dim distkm As Double
Dim brngrad As Double
Dim brngdeg As Double
Dim ER As Single
ER = 6371
' Converting coordinates (degrees) to coordinates (radians) through another function I built, works great
Lat1rad = Deg2Rad(Lat1)
Lat2rad = Deg2Rad(Lat2)
Lon1rad = Deg2Rad(Lon1)
Lon2rad = Deg2Rad(Lon2)
' This part works great
distrad = Math.Acos(Math.Sin(Lat1rad) * Math.Sin(Lat2rad) + Math.Cos(Lat1rad) * Math.Cos(Lat2rad) * Math.Cos(Lon2rad - Lon1rad))
distkm = distrad * ER
dbdistm = distkm * 1000
' This part doesnt
brngrad = Math.Atan2(Math.Cos(Lat1rad) * Math.Sin(Lat2rad) - Math.Sin(Lat1rad) * Math.Cos(Lat2rad) * Math.Cos(Lon2rad - Lon1rad), Math.Sin(Lon2rad - Lon1rad) * Math.Cos(Lat2rad))
brngdeg = Rad2Deg(brngrad)
dbbrng = brngdeg
End Sub
Ive double and triple checked the formula and to my eyes it looks identical to the excel formula. I even put the same coordinates into excel and got the correct answer. Im stumped! Please help!
Last edited by keycat; Dec 1st, 2010 at 09:02 AM.
-
Dec 1st, 2010, 01:20 PM
#2
Re: [RESOLVED] VB Math.Atan2 not providing proper answer.. HELP!
Not that it matters much, but from my experience the VB-style argument order is much more common. I have no idea why Excel decided to be the odd one out. Having y first makes sense since Atan(y/x), ignoring the special cases Atan2 takes care of, gives the angle that <x,y> makes with the x-axis.
The time you enjoy wasting is not wasted time.
Bertrand Russell
<- Remember to rate posts you find helpful.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|