Home > Back-end >  Midpoint between 2 coordinates
Midpoint between 2 coordinates

Time:11-11

I am trying to calculate the midpoint between 2 coordinates that are located a few meters from each other so it is not relevant the curvature of the earth. I am using the method below that should work:

def compute_midPoint(lat1,lon1,lat2,lon2):  
  return ((lat1   lat2)/2, (lon2   lon2)/2)

However the result is not accurate. Doing same operation manually I get the correct result. The difference in results is slightly different, would you know what I am missing?

Example:

compute_midPoint(53.2604111, -2.1279681, 53.2600830, -2.1271415)
Python result: 53.260247050000004, -2.1271415 X

MANUAL TESTING √
1065204941/2 = 53.2602470
42551096/2 = -2.1275548

CodePudding user response:

Your longitude calculation is wrong, (lon2 lon2)/2 - that works out to be just lon2.

It needs to be (lon1 lon2)/2 instead. The latitude is close enough, though you may want to restrict the number of decimals when printing it out. You can limit it to seven decimal places with an f-string like f"{123.4567890123456789:.7f}" which will give you the string 123.4567890.

CodePudding user response:

From python documentation:

"Floating-point numbers are represented in computer hardware as base 2 (binary) fractions. For example, the decimal fraction

Unfortunately, most decimal fractions cannot be represented exactly as binary fractions. A consequence is that, in general, the decimal floating-point numbers you enter are only approximated by the binary floating-point numbers actually stored in the machine."

https://docs.python.org/3/tutorial/floatingpoint.html

  • Related