logo
down
shadow

Making function for calculating distance


Making function for calculating distance

Content Index :

Making function for calculating distance
Tag : python , By : Marcos de Carvalho
Date : November 26 2020, 03:01 PM

I wish this helpful for you Using solutions provided in Getting distance between two points based on latitude/longitude and Iterate a list as pair (current, next) in Python I was able to build a Pythonic approach of this problem:
import itertools

from collections import namedtuple
from math import sin, cos, sqrt, atan2, radians

Location = namedtuple('Location', ['long', 'lat', 'time'])
all_locations = [
    Location(lat=37.481236, long=126.952733, time=1488323400),
    Location(lat=37.310045, long=127.101255, time=1488323255),
    Location(lat=37.383065, long=126.672596, time=1488323531),
    Location(lat=37.383065, long=116.672596, time=1488323230),
]


def distance(loc_a, loc_b):
    """Extracted from: https://stackoverflow.com/questions/19412462"""
    R = 6373.0

    lat_a, lat_b = radians(loc_a.lat), radians(loc_b.lat)
    long_a, long_b = radians(loc_a.long), radians(loc_b.long)
    dlat = lat_b - lat_a
    dlong = long_b - long_a

    a = sin(dlat / 2)**2 + cos(lat_a) * cos(lat_b) * sin(dlong / 2) ** 2
    c = 2 * atan2(sqrt(a), sqrt(1 - a))

    return R * c


def pairwise(iterable):
    """Extracted from: https://stackoverflow.com/questions/5434891"""
    a, b = itertools.tee(iterable)
    next(b, None)
    return zip(a, b)


sorted_locations = sorted(all_locations, key=lambda l: l.time)
total_distance = sum(distance(a, b) for a, b in pairwise(sorted_locations))
delta_time = sorted_locations[-1].time - sorted_locations[0].time
print(total_distance, delta_time, total_distance / delta_time)
sorted_locations = [l1, l2, l3]
distances = [distance(a, b) for a, b in pairwise(sorted_locations)]
# equivalent to [distance(l1, l2), distance(l2, l3)]
total_distance = sum(distances)

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Trouble calculating the distance function in bezier clipping


Tag : java , By : Bharath
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Your distance function should not necessarily be anywhere near your two original curves: It's using a completely different coordinate system, i.e. t vs D, as opposed to your original curves using x and y. [edit] i.e. t only goes up to 1.0, and measures how far along, as a ratio of the total length, you are along your curve, and D measuring the distance your curve2 is from curve1's baseline.
Also, when you say ""distance function" between curve1 and a "baseline" of curve2" I think you've mixed up curve1 and curve2 here as in your code you are clearly using the baseline of curve1.

MySQL Function for calculating Haversine Distance


Tag : mysql , By : user104292
Date : March 29 2020, 07:55 AM
seems to work fine all. , Okay.
Solved it.
 DELIMITER $$
 CREATE FUNCTION haversineDistance
                 (
                  lat1 VARCHAR(256), 
                  long1 VARCHAR(256), 
                  lat2 VARCHAR(256), 
                  long2 VARCHAR(256))
 RETURNS FLOAT DETERMINISTIC
 BEGIN

      DECLARE radLat1 FLOAT;
      DECLARE radLong1 FLOAT;
      DECLARE radLat2 FLOAT;
      DECLARE radLong2 FLOAT;
      DECLARE dLat FLOAT;
      DECLARE dLong FLOAT;
      DECLARE cordLength FLOAT;
      DECLARE centralAngle FLOAT;
      DECLARE distance FLOAT;

      SET radLat1 = CAST(lat1 AS DECIMAL(10,10)) * PI() / 180;
      SET radLong1 = CAST(long1 AS DECIMAL(10,10)) * PI() / 180;
      SET radLat2 = CAST(lat2 AS DECIMAL(10,10)) * PI() / 180;
      SET radLong2 = CAST(long2 AS DECIMAL(10,10)) * PI() / 180;
      SET dLat = radLat2 - radLat1;
      SET dLong = radLong2 - radLong2;
      SET cordLength = POW(SIN(dLat/2),2)+COS(lat1)*COS(lat2)*POW(SIN(dLon/2),2);
      SET centralAngle = 2 * ATAN2(SQRT(cordLength), SQRT(1-cordLength));
      SET distance = 6367 * centralAngle;

      RETURN distance;
 END

Calculating distance between 2 zips by using a function


Tag : sql-server , By : Michael T.
Date : March 29 2020, 07:55 AM
Hope this helps I have a table of which first 3 rows look like: , Please Modify your query as below:
        SELECT IDENTITY(INT, 1, 1) ID
            ,*
            ,CAST(0 AS FLOAT) dist1
            ,CAST(0 AS FLOAT) DIST2
        INTO #TEMP
        FROM #zip

        DECLARE @COUNT INT
        ,@DIST1 FLOAT
        ,@DIST2 FLOAT
        ,@MAXID INT

        SET @COUNT = 1

        SELECT @MAXID = MAX(ID)
        FROM #TEMP

        WHILE (@COUNT <= @MAXID)
        BEGIN
            SELECT @DIST1 = dbo.ufnzipcodedist_2012(z1, z2)
                ,@DIST2 = dbo.ufnzipcodedist_2012(z2, z3)
            FROM #TEMP
            WHERE ID = @COUNT

            UPDATE t
            SET T.DIST1 = @DIST1
                ,t.DIST2 = @DIST2
            FROM #TEMP t
            WHERE ID = @COUNT

            SET @COUNT = @COUNT + 1
        END

        SELECT *
        FROM #TEMP

Calculating the distance between ZIP Codes in R with the mapdist function


Tag : r , By : Ivan Kitanovski
Date : March 29 2020, 07:55 AM
it helps some times It could be that the zip code on its own is ambiguous. If you include 'USA' in the search string it works
library(ggmap)

mapdist(from = c("19111, USA"), to = c("19187, USA"))


#         from         to     m    km    miles seconds  minutes     hours
# 1 19111, USA 19187, USA 21420 21.42 13.31039    1976 32.93333 0.5488889
library(googleway)

set_key("your_api_key")

google_distance(origins = c("19111, USA"), 
                destinations = c("19187, USA"))

# $destination_addresses
# [1] "Philadelphia, PA 19187, USA"
# 
# $origin_addresses
# [1] "Philadelphia, PA 19111, USA"
# 
# $rows
# elements
# 1 21.4 km, 21420, 33 mins, 1976, 35 mins, 2101, OK
# 
# $status
# [1] "OK"

Help with a member function calculating distance


Tag : cpp , By : toki
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • some coordinates that I extracted from geocoder in Python are not saving in the variable I created
  • 7C in cs circles- python Im not sure what is wrong with this yet
  • How to fix 'AttributeError: 'list' object has no attribute 'shape'' error in python with Tensorflow / Keras when loading
  • python - thread`s target is a method of an object
  • Retrieve Variable From Class
  • What is the reason for matplotlib for printing labels multiple times?
  • Why would people use ThreadPoolExecutor instead of direct function call?
  • When clear_widgets is called, it doesnt remove screens in ScreenManager
  • Python can't import function
  • Pieces doesn't stack after one loop on my connect4
  • How to change font size of all .docx document with python-docx
  • How to store a word with # in .cfg file
  • How to append dictionaries to a dictionary?
  • How can I scrape text within paragraph tag with some other tags then within the paragraph text?
  • Custom entity ruler with SpaCy did not return a match
  • Logging with two handlers - one to file and one to stderr
  • How to do pivot_table in dask with aggfunc 'min'?
  • This for loop displays only the last entry of the student record
  • How to split a string by a specific pattern in number of characters?
  • Python 3: how to scrape research results from a website using CSFR?
  • Setting the scoring parameter of RandomizedSeachCV to r2
  • How to send alert or message from view.py to template?
  • How to add qml ScatterSeries to existing qml defined ChartView?
  • Django + tox: Apps aren't loaded yet
  • My css and images arent showing in django
  • Probability mass function sum 2 dice roll?
  • Cannot call ubuntu 'ulimit' from python subprocess without using shell option
  • Dataframe Timestamp Filter for new/repeating value
  • Problem with clicking select2 dropdownlist in selenium
  • pandas dataframe masks to write values into new column
  • How to click on item in navigation bar on top of page using selenium python?
  • Add multiple EntityRuler with spaCy (ValueError: 'entity_ruler' already exists in pipeline)
  • error when replacing missing ')' using negative look ahead regex in python
  • Is there a way to remove specific strings from indexes using a for loop?
  • select multiple tags by position in beautifulSoup
  • pytest: getting AttributeError: 'CaptureFixture' object has no attribute 'readouterror' capturing stdout
  • Shipping PyGObject/GTK+ app on Windows with MingW
  • Python script to deduplicate lines in multiple files
  • How to prevent window and widgets in a pyqt5 application from changing size when the visibility of one widget is altered
  • How to draw stacked bar plot from df.groupby('feature')['label'].value_counts()
  • Python subprocess doesn't work without sleep
  • How can I adjust 'the time' in python with module Re
  • Join original np array with resulting np array in a form of dictionary? multidimensional array? etc?
  • Forcing labels on histograms in each individual graph in a figure
  • For an infinite dataset, is the data used in each epoch the same?
  • Is there a more efficent way to extend a string?
  • How to calculate each single element of a numpy array based on conditions
  • How do I change the width of Jupyter notebook's cell's left part?
  • Measure distance between lat/lon coordinates and utm coordinates
  • Installing megam for NLTK on Windows
  • filter dataframe on each value of a samn column have a specific value of another column in Panda\Python
  • Threading with pubsub throwing AssertionError: 'callableObj is not callable' in wxPython
  • Get grouped data from 2 dataframes with condition
  • How can I import all of sklearns regressors
  • How to take all elements except the first k
  • Whats wrong with my iteration list of lists from csv
  • Tensorflow Estimator API save image summary in eval mode
  • How to Pack with PyQt - how to make QFrame/Layout adapt to content
  • How do I get certain Time Range in Python
  • python doubly linked list - insertAfter node
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com