I have two variables which define a static longitude and latitude. I want to be able to define a multi dimensional array which holds the following: id, longitude and latitude.
What i want to achieve - from the static longitude to feed through the loop of arrays and if finds something within a radius of 50 miles (or whatever), it selects the potential ones and lists them.
I am not sure what formula or algorithm i can use to check the radius and bring back the nearest values.
Please note: not using databases in this example.
So far:
$mainLong = 57.7394571;
$mainLat = -4.386997;
$main = array(
array("loc_1",57.7394571,-4.686997),
array("loc_2",51.5286416,-0.1015987),
array("loc_3",51.2715146,-0.3953564),
array("loc_4",50.837418,-0.1061897)
);
foreach ( $main as $key => $value ) {
if($value[1] == $mainLong){
print_r($value);
}
}
Haversine formula could help.
Here is a sample algorithm.
You can try it out.
%% Begin calculation
R = 6371; % Earth's radius in km
delta_lat = locs{2}(1) - locs{1}(1); % difference in latitude
delta_lon = locs{2}(2) - locs{1}(2); % difference in longitude
a = sin(delta_lat/2)^2 + cos(locs{1}(1)) * cos(locs{2}(1)) * ...
sin(delta_lon/2)^2;
c = 2 * atan2(sqrt(a), sqrt(1-a));
km = R * c; % distance in km
%% Convert result to nautical miles and miles
nmi = km * 0.539956803; % nautical miles
mi = km * 0.621371192; % miles
Related
I was wondering in this example that I've used to practice for loops, I needed to change this code in order to change the image that looks like this, some basic golden angle plot:
to this example
phi = (sqrt(5)+1)/2;% Número áureo %Golden Number
golden_angle = 2*pi/phi;
max_angle = 10000;
theta = 1:golden_angle:max_angle;% ángulo %Angle
r = sqrt(theta);% radio %Radius
[x,y] = pol2cart(theta,r);% coordenadas polares a cartesianas %Polar to cartesian
figure
plot(x,y,'.','MarkerSize',10);axis off;
I know that the number next to 'MarkerSize' wides the flower petals, but I tried changing theta values in the array but with no particular result, only I’ve changed color but not the size. I also tried making these a for cycle, that creates circles as the golden flower petals, I think, but don't know how to implement it. But how to make them more and more small at the iteration goes?, and I think total number of petals is 2575.
for i = 1:10
%plot(x,y,'.',x(i),y(i),'.','MarkerSize',10*abs(y(i)),'MarkerFaceColor','g')
You can use scatter in place of plot: scatter allows to set the marker size as a parameter:
phi = (sqrt(5)+1)/2;% Número áureo %Golden Number
golden_angle = 2*pi/phi;
max_angle = 10000;
theta = 1:golden_angle:max_angle;% ángulo %Angle
r = sqrt(theta);% radio %Radius
marker_size = 10 * r / sqrt(max_angle); % new
[x,y] = pol2cart(theta,r);% coordenadas polares a cartesianas %Polar to cartesian
figure
scatter(x,y,marker_size, 'fill'); axis off; % new: scatter
marker_size data look good on table, increasing from 0 to 10 with theta.
However, on my Matlab (R2013b), the rendering is very gross.
I have two points on a map -
val point1 : LatLng(13.3016139,77.4219107)
val point2 : LatLng(14.1788932,77.7613413)
I want to calculate and find 100 equidistant points along a straight line between these two coordinates. How do I do that?
ps. I'm sure this has been asked before, I just can't find it.
Equidistant, and more importantly, straight by which projection?
usually, to find a distance in cartesian space one would use something like the
Haversine formula to find a value, as previously answered in stack answer: How to convert latitude or longitude to meters?
As for the equidistant part, once you have the distance decided as per your taste of the shape and radius of Earth at given points, a simple division will do. .
python 3.7
>>> dist = 5427 #just some number
>>> nbr_o_points = 101
>>> points = [(dist/nbr_o_points)*(i+1) for i in range(nbr_o_points)]
>>> [f'{p:.2f}' for p in points]
['53.73', '107.47', '161.20',..., '5319.53', '5373.27', '5427.00']
Now to transfer these distances from point a to b back onto the desired projection... This is not part of your question... Stack - how-to-determine-vector-between-two-lat-lon-points might help.
take the vector and multiply by the dists in points in order to get your coordinates.
This is how I solved it -
fun findEquidistantPoints(latLng1: LatLng, latLng2: LatLng, pointCount: Int): ArrayList<LatLng> {
if (pointCount < 0)
throw IllegalArgumentException("PointCount cannot be less than 0")
val points = ArrayList<LatLng>()
val displacement = latLng1.displacementFromInMeters(latLng2)
val distanceBetweenPoints = displacement / (pointCount + 1)
for (i in 1..pointCount) {
val t = (distanceBetweenPoints * i) / displacement
points.add(LatLng(
(1 - t) * latLng1.latitude + t * latLng2.latitude,
(1 - t) * latLng1.longitude + t * latLng2.longitude
))
}
return points
}
I am completely new to GeoDjango, and I am trying to calculate distances between objects.
I am doing everything as per this post https://coderwall.com/p/k1gg1a/distance-calculation-in-geodjango , but my results differ from what Google Maps tell me.
When I try to calculate distance between London and Paris, I get this
london = GEOSGeometry('POINT(-0.056922 51.480415)', srid=4326)
paris = GEOSGeometry('POINT(2.350918 48.867744)', srid=4326)
london = london.transform(900913, clone=True)
paris = paris.transform(900913, clone=True)
print(london.distance(paris))
>>> 527450.6633622452
Which looks like it's about 527 km.
However, Google Maps tell me that the distance is 341 km:
What am I doing wrong?
You're not doing anything wrong. Google maps is (I think) returning the Great Circle Distance while GEOS (which is an acronym for Geometry Engine - Open Source) is returning the Euclidean distance (GEOS is more about geometry and topology than geography). If you want to approximate the Great Circle Distance, you could try the Haversine Formula with the following code taken from this question:
>>>from math import radians, cos, sin, asin, sqrt
...
>>>def haversine(lon1, lat1, lon2, lat2):
... # convert decimal degrees to radians
... lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
... # haversine formula
... dlon = lon2 - lon1
... dlat = lat2 - lat1
... a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
... c = 2 * asin(sqrt(a))
... r = 6371 # Radius of earth in kilometers. Use 3956 for miles
... return c * r
>>>haversine(-0.056922, 51.480415, 2.350918, 48.867744)
>>>337.303...
I was solving a exercise of a online course form coursera on machine learning. The problem statement is :
Suppose that a high school has a dataset representing 40 students who were admitted to college and 40 students who were not admitted. Each ( x(i), y(i) ) training example contains a student's score on two standardized exams and a label of whether the student was admitted.
Our task is to build a binary classification model that estimates college admission chances based on a student's scores on two exams. In the training data,
a. The first column of your x array represents all Test 1 scores, and the second column represents all Test 2 scores.
b. The y vector uses '1' to label a student who was admitted and '0' to label a student who was not admitted.
I have solved it by using predefined function named fminunc. Now , i am solving it by using gradient descent but my graph of cost vs number of iteration is not conversing i.e cost function value is not decreasing with number of iteration . My theta value is also not matching with the answer that should i get.
theta value that i got :
[-0.085260 0.047703 -0.022851]
theta value that i should get (answer) :
[-16.38 0.1483 0.1589]
My source code :
clear ; close all; clc
x = load('/home/utlesh/Downloads/ex4x.txt');
y = load('/home/utlesh/Downloads/ex4y.txt');
theta = [0,0,0];
alpha = 0.00002;
a = [0,0,0];
m = size(x,1);
x = [ones(m,1) x];
n = size(x,2);
y_hyp = y*ones(1,n);
for kk = 1:100000
hyposis = 1./(1 + exp(-(x*theta')));
x_hyp = hyposis*ones(1,n);
theta = theta - alpha*1/m*sum((x_hyp - y_hyp).*x);
a(kk,:) = theta ;
end
cost = [0];
for kk = 1:100000
h = 1./(1 + exp(-(x*a(kk,:)')));
cost(kk,:) = sum(-y .* log(h) - (1 - y) .* log(1 - h));
end
x_axis = [0];
for kk = 1:100000
x_axis(kk,:) = kk;
end
plot(x_axis,cost);
The graph that i got looks like that of 1/x;
Please tell me where i am doing mistake . If there is anything that i misunderstood please let me know .
What I can see missing is the usage of learning rate and weights. The weights can be adjusted in two modes online and batch.
The weights should be randomly assigned values between [-0.01,0.01]. I did an exercise as a part of my HW during my Master's. Below is the snippet:
assign values to weights between [-0.01,0.01] i.e. no. of weight values will be, no. of features + 1:
weights = -.01 + 0.02 * rand(3,1);
learnRate = 0.001;
Here running the code for set number of iterations: (It converged in 100 iterations also).
while iter < 100
old_output = new_output;
delta = zeros(cols-1,1);
for t = 1:rows
input = 0;
for j = 1:cols-1
input = input + weights(j) * numericdata(t,j);
end
new_output(t) = (1 ./ (1 + exp(-input)));
for j = 1:cols-1
delta(j) = delta(j) + (numericdata(t,4)-new_output(t)) * numericdata(t,j);
end
end
#Adjusting weights (Batch Mode):
for j=1:cols-1
weights(j) = weights(j) + learnRate * (delta(j));
end
error = abs(numericdata(:,4) - new_output);
errorStr(i) = (error(:));
error = 0;
iter = iter + 1;
i = i + 1;
end
Also, I had a talk with my professor, while studying it. He said, if the dataset given has the property to converge then you will see that when you randomly run it for different number of iterations.
I have began working on an autonomous rc helicopter in c. I need help finding a way to calculate the bearing acuratley. I am using two sets of coordinates (latitude and longitude), one is the current location and the other is the destination point. I have converted the latitude and longitude into decimal format so....
40°58'19.86"N = 40.972183
74°14'52.74"W = 74.247983
Can anyone show me code in c to find the bearing or a formula i can use?
i have looked at: http://www.movable-type.co.uk/scripts/latlong.html and when i transfer it to c, the results make no sense.
This is what i have tried:
double x = Sin(Longitude2 - Longitude1) * Cos(Latitude2);
double y = Cos(Latitude1) * Sin(Latitude2) - Sin(Latitude1) * Cos(Latitude2) * Cos(Longitude2 - Longitude1);
double heading = (Atan2(x, y) % 2 * 3.14159265) (180/3.14159265);
Have you converted your coordinates from degrees to radians before calculations ?
angleRad = 3.14159265 * angleDeg / 180;
And
bearing = Atan2(y, x);
in that website.
The bearing should be converted from rad to deg in turn:
bearing = 180 * bearing / 3.14159265;
and in case of negative value eventually:
bearing = bearing + 360;
I don't know how to write this using the convention above (with "%").
Latitude1 and Longitude1 are coordinates of the observer
Latitude2 and Longitude2 are coordinates of destination point.
Formulas from that website work well.
For the very small area you are considering you can assume the world is flat.
If you also only need this to work locally you can pre-calculate the value of a deg lat/lon on the ground in metres (or ft)
Then simply convert the delta lat/lon into distance and do the normal trig.
To convert distance to lat/lon you can either use google earth to measure it or
How to convert latitude or longitude to meters?