Haversine Formula still not working - javascript

I used harversine formula to calculate if points are inside/outside of circle, but still it response that points are inside of the circle, it must be outside the circle. Take a look at my code.
var xp = 7.070562277980709; // point_lat
var yp = 125.60755640475463; // point_long
var radius = 63.942490126300555; // radius
var xc = 7.070479805752504; // circle_lat
var yc = 125.60851603754577; // circle_lon
var r = radius / 1000; // convert meter to kilometer
var dlat = (xp - xc) * (Math.PI / 180);
var dlng = (yp - yc) * (Math.PI / 180);
var a = ((Math.sin(dlat / 2)) * (Math.sin(dlat / 2)));
var b = ((Math.cos(xp * (Math.PI / 180))) * (Math.cos(xc * (Math.PI / 180))));
var c = ((Math.sin(dlng / 2)) * (Math.sin(dlng / 2)));
var d = a + (b * c);
var e = 2 * Math.atan2(Math.sqrt(d), Math.sqrt(1 - d));
var f = r * e;
if (f < r) {
alert('INSIDE');
} else if(f > r) {
alert('OUTSIDE');
}
this function should alert me "OUTSIDE". Whats wrong with this code?? Thanks for your help.
All points are given by google map. And the default unit of radius of google map is meter, thats why I converted it to kilometer.

In the formula you are using, the radius is the Earth's radius. The formula gives the great circle (i.e. shortest) distance between two points on the Earth's surface.
Using 63.942490126300555 for the radius, then dividing it by 1,000 gives an f of 0.0000010667905687961212 km or 0.001 m or 1 mm.
Substituting a more appropriate value for r (e.g. 6,371) gives an f of 0.10629117978319975 km, or 106.291 metres.
Calculating it another way, since the coordinates are close to the equator, you can work out the distances as fractions of the Earth's circumference and use plain trigonometry.
Using a circumference of 40,000 km, the difference in latitude is 0.0000824722282057877 degrees, which is:
dLat = 40,000 km * 0.0000824722282057877 / 360
or
dLat = 0.009163580911754189 km
= 9.164 m
and for longitude:
dLong = 0.0009596327911367553;
dist = 40000 * 0.0009596327911367553 / 360;
= 0.10662586568186169 km
= 106.626 m
And a bit of basic trig:
dist = sqrt(9.164^2 + 106.626^2)
= 0.10629117978319975 km
= 106.291 m
which is pretty close to the other result. You can use that method quite successfully for small distances, just multiply the distance derived from the difference in longitude by the cosine of the latitude (since angular distances get shorter as you get closer to the pole).
My comment was just a dig at your spelling of "metre". :-)
Edit
Here's a function to return the great circle distance based on the Haversine formula at Movable Type Scripts:
// Return the great circle distance between two points on
// the Earth's surface given their latitude and longitude in
// decimal degrees. Only approximate.
function greatCircleDistance(lat0, lon0, lat1, lon1) {
// Approximate Earth radius
var earthRadius = 6.371e3; // 6,371,000 m
// Convert args to radians
for (var i=arguments.length; i; ) {
arguments[--i] = arguments[i] * Math.PI/180;
}
// Do calculation
var dLat = lat1 - lat0;
var dLon = lon1 - lon0;
var a = Math.pow(Math.sin(dLat/2),2) +
Math.cos(lat0) * Math.cos(lat1) *
Math.pow(Math.sin(dLon/2),2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return earthRadius * c;
}
var xp = 7.070562277980709; // point_lat
var yp = 125.60755640475463; // point_long
var xc = 7.070479805752504; // circle_lat
var yc = 125.60851603754577; // circle_lon
console.log(greatCircleDistance(xp, yp, xc, yc)); // 0.10629117978188952
So you can do:
if ( greatCircleDistance(xp, yp, xc, yc) > 63) {
console.log('outside');
} else {
console.log('inside');
}

It is obvious that your Harversine calculation is correct and it is equal to the result returned by google map api static method computeDistanceBetween. Here is a fiddle.
However your logic implies that both the radius of sphere and radius within which you want to check if a point exists, are same.
To get the expected output you must model your problem space as below
R : radius of sphere
p1, p2... : points(lat,long co-ordinates) on the surface of sphere
r: to check whether p2 lies within distance 'r' of p1 where r & R in the same unit
Based on above you need to implement below logic
var e = calculate haversine of the central angle for point p1 and p2
var d = e * R;//where R is the radius of sphere, and the d would be great circle distance
if( d < r){// check whether p1 exists within r distance of p2
//point is inside
}
else{
//point is outside
}
Note that Haversine formula is not only for earth distance, rather it is for spherical body. However the correctness may differ based on size and position of the points under consideration.

Related

Calculate distance on the basis of Angle and Maximum Range

I am working on javascript code where I need to find out distance on the basis of Angle, Initial Height, Velocity, Maximum Range.
Example: If an object shoots from the ground (where height = 0) at the angle 45 degree and with the velocity of 3000. The Object drops at distance 1500 meter far from the point where it was thrown.
What will be the distance from the shooting point to dropping point on the ground, if the object shoots from same height and velocity but at the angle of 60 degree.
Initial Height => h = 0
Angle => a = 45 degree
Velocity => v = 3000
Max Range => m = 1500 meter
var h = 0;
var a = 45;
var v = 3000;
var m = 1500;
var d = null; //need to calculate this
// Range calculation formula is: d = V₀² * sin(2 * α) / g
d = v * v * Math.sin(2 * a) / 9.8;
I am getting Range from above formula but that's not on the basis of given maximum range.
The function Math.sin expects that the angle is given in radian. Given an angle α in degree, you can compute the angle in radian by α * (π/180). Thus, your computation needs to be performed as follows.
d = v * v * Math.sin(2 * a * Math.PI / 180) / 9.8;
Note, your maximum range is actually ≈920000 m. Your initial velocity is 10800 km/h (or 6710 mph), which is 10 times as fast as a commercial air plane.

Find the final latitude longitude after a movement on the globe

I am using the Haversine formula to calculate the distance from two latitude-longitude pairs.
function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1);
var dLon = deg2rad(lon2-lon1);
var lat1 = deg2rad(lat1);
var lat2 = deg2rad(lat2);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) *
Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d;
}
Given a starting point (lat1, lat2), the distance required to move on a straight line and the angle, I need to determine the endpoint (as in lat2 and lon2).
See my attempt below:
function getFinalLatLon(lat1, lon1, distance, angle) {
var R = 6371; // Radius of the earth in km
var c = distance/R;
// Math.atan2(Math.sqrt(a), Math.sqrt(1-a)) = c/2
var a = // stuck here
// looking for this part of the code
return [lat2, lon2];
}
If you are moving horizontally, you can increment the longitude by distance / (R * cos(lat)). No atan needed.
EDIT: Since you wanted a formula for the general case, consider the following geometric derivation:
Front view:
Side view:
Entire setup:
Notes:
r is the unit vector of your starting position, and s is the endpoint.
a, b, c are intermediate vectors to aid calculation.
(θ, φ) are the (lat, long) coordinates.
γ is the bearing of the direction you are going to travel in.
δ is the angle travelled through (distance / radius R = 6400000m).
We need a, b to be perpendicular to r and also a aligned with North. This gives:
c is given by (simple trigonometry):
And thus we get s (through some very tedious algebra):
Now we can calculate the final (lat, long) coordinates of s using:
Code:
function deg2rad(deg) { return deg * (Math.PI / 180.0) }
function rad2deg(rad) { return rad * (180.0 / Math.PI) }
function getFinalLatLong(lat1, long1, distance, angle, radius) {
// calculate angles
var delta = distance / radius,
theta = deg2rad(lat1),
phi = deg2rad(long1),
gamma = deg2rad(angle);
// calculate sines and cosines
var c_theta = Math.cos(theta), s_theta = Math.sin(theta);
var c_phi = Math.cos(phi) , s_phi = Math.sin(phi) ;
var c_delta = Math.cos(delta), s_delta = Math.sin(delta);
var c_gamma = Math.cos(gamma), s_gamma = Math.sin(gamma);
// calculate end vector
var x = c_delta * c_theta * c_phi - s_delta * (s_theta * c_phi * c_gamma + s_phi * s_gamma);
var y = c_delta * c_theta * s_phi - s_delta * (s_theta * s_phi * c_gamma - c_phi * s_gamma);
var z = s_delta * c_theta * c_gamma + c_delta * s_theta;
// calculate end lat long
var theta2 = Math.asin(z), phi2 = Math.atan2(y, x);
return [rad2deg(theta2), rad2deg(phi2)];
}
Test cases:
Input (lat, long) = (45, 0), angle = 0, distance = radius * deg2rad(90) => (45, 180) (as I said before)
Input (lat, long) = (0, 0), angle = 90, distance = radius * deg2rad(90) => (0, 90) (as expected - start at equator, travel east by 90 longitude)
Input (lat, long) = (54, 29), angle = 36, distance = radius * deg2rad(360) => (54, 29) (as expected - start at any random position and go full-circle in any direction)
Interesting case: input (lat, long) = (30, 0), everything else same. => (0, 90) (we expected (30, 90)? - not starting at equator, travel by 90 degrees to North)
The reason for this is that 90 degrees to North is not East (if you're not at the equator)! This diagram should show why:
As you can see, the path of movement at 90 degrees to the North is not in the direction of East.
I just found a similar question here and I followed the solution to come up with a function that works for my case.
Hope it helps someone else:
function getFinalLatLon(lat1, lon1, distance, angle){
function deg2rad(deg) {
return deg * (Math.PI/180)
}
// dy = R*sin(theta)
var dy = distance * Math.sin(deg2rad(angle))
var delta_latitude = dy/110574
// One degree of latitude on the Earth's surface equals (110574 meters
delta_latitude = parseFloat(delta_latitude.toFixed(6));
// final latitude = start_latitude + delta_latitude
var lat2 = lat1 + delta_latitude
// dx = R*cos(theta)
var dx = distance * Math.cos(deg2rad(angle))
// One degree of longitude equals 111321 meters (at the equator)
var delta_longitude = dx/(111321*Math.cos(deg2rad(lat1)))
delta_longitude = parseFloat(delta_longitude.toFixed(6));
// final longitude = start_longitude + delta_longitude
var lon2 = lon1 + delta_longitude
return [lat2, lon2];
}
The angle is 0 degrees for a horizontal move. You can switch that as you wish. If someone is moving north that would be 90 deg. 135 degrees for north west and so on...

Problems With Vector Reflection with Particle Collisions

I was wondering whether I made a math mistake in my particle collision simulation found here.
The particles don't seem to separate properly during collision resolution. Here is a code snippet from the function which separates particles and changes their velocities:
//particle 1
var pi = particles[i];
//particle 2
var pj = particles[j];
//particle 1 to particle 2
var pimpj = pi.mesh.position.clone().sub(pj.mesh.position);
//particle 2 to particle 1
var pjmpi = pj.mesh.position.clone().sub(pi.mesh.position);
//if colliding (radius is 20)
if(pimpj.length() < 20 && pimpj.length() != 0)
{
//reflect velocity off of 1->2
pi.velocity = pi.velocity.reflect(pimpj.clone().normalize()).multiplyScalar(restitution);
//reflect velocity off of 2->1
pj.velocity = pj.velocity.reflect(pjmpi.clone().normalize()).multiplyScalar(restitution);
//move particle 1 to appropiate location based off of distance in between
var pip = pi.velocity.clone().normalize().multiplyScalar(20-pimpj.length());
//move particle 2
var pjp = pj.velocity.clone().normalize().multiplyScalar(20-pimpj.length());
pi.mesh.position.add(pip);
pj.mesh.position.add(pjp);
}
I have tried reversing pimpj with pjmpi while changing pi.velocity, but to no effect.
note: I am using three.js
Firstly, the particle collisions you seem to be looking for are Elastic collisions, for which there is maths covering the calculation of the velocities after a collision.
The collision is simplest in the centre of momentum frame, so if you first calculate that frame V = (m1v1 + m2v2)/(m1+m2), then you can subtract it from both particles, do a simple symmetric collision and add the frame velocity back on afterwards.
From there, calculate the velocities using the formulae in the 2 & 3d section of that page.
Specific points on your code:
pimpj = -pjmpi, so you don't need both
A collision occurs when the paths between the last frame and this frame got too close; if you only check the distance at each frame you will have problems where particles fly through each other at high speed, and that you have to keep shifting their positions because they are already overlapping when you detect the collision.
Ideally calculate the positions on impact and use those to redirect them.
For speed, only calculate pimpj.clone().normalize() once, and store it - you're not changing this direction unit vector later, so you don't need to keep recalculating it, or calculating pjmpi-derived equivalents (see #1)
I think part of the problem is that your model of collision is overly simplistic. The basic rules for collision are conservation of momentum and conservation of energy. Looking at the 1D case. If both particles have the same mass m and u1 and u2 are you velocities beforehand and v1, v2 are the velocities after then
m u1 + m2 u2 = m v1 + m v2
conservation of energy for a perfect collision gives
1/2 m u1.u1 + 1/2 m u2.u2 = 1/2 m v1.v1 + 1/2 m v2.v2.
These two equations have the solution v1 = u2, v2 = u1. That is the velocities switch. In particular if one velocity is zero before collision then after collision the other velocity becomes zero after the collision. You can see this happen when using a newton's cradle.
In 2D we can resolve in a coordinate system with 1 direction along to the plane of contact and one direction perpendicular to it. The force only occurs in the perpendicular direction, this means the velocities along the pane don't change but the perpendicular velocities switch.
var u = pjmpi.clone().normalize();
var v = new THREE.Vector3(u.y,-u.x,0);
// resolve in two directions
var piu = pi.velocity.dot(u);
var piv = pi.velocity.dot(v);
pi.velocity = new THREE.Vector3(
pju * u.x + piv * v.x,
pju * u.y + piv * v.y,
0);
pj.velocity = new THREE.Vector3(
piu * u.x + pjv * v.x,
piu * u.y + pjv * v.y,
0);
That works for a perfectly elastic collision. See Wikipedia elastic collision which has an nice illustration. The formula at the end simplifies a bit if you take the masses equal.
For an partially inelastic collision with restitution R we can look at the end of http://www.plasmaphysics.org.uk/collision2d.htm. Now take the velocity of the center of mass w. This will not change after the collision because the total momentum is conserved. So w=(u1+u2)/2 = (v1+v2)/2. Take the velocities relative to this center of mass
v1' = v1-w, v2' = v2-w, apply the restitution v1'' = R (v1'-w), v2'' = R(v2'-w) and add the velocity of the center of mass.
v1''' = R(v1-v2)/2 + (v1+v2)/2
v2''' = R(v1-v2)/2 + (v1+v2)/2
Also see wikipedia Inelastic collision which has the same formula in 1D.
This translate to code as
var u = pjmpi.clone().normalize();
var v = new THREE.Vector3(u.y,-u.x,0);
// resolve in two directions
var piu = pi.velocity.dot(u);
var piv = pi.velocity.dot(v);
var pju = pj.velocity.dot(u);
var pjv = pj.velocity.dot(v);
// velocities after collision
var v1x = pju * u.x + piv * v.x;
var v1y = pju * u.y + piv * v.y;
var v2x = piu * u.x + pjv * v.x;
var v2y = piu * u.y + pjv * v.y;
// vel center of mass
var wx = (v1x+v2x)/2;
var wy = (v1y+v2y)/2;
// difference
var dx = (v1x-v2x)/2;
var dy = (v1y-v2y)/2;
// final velocities
pi.velocity = new THREE.Vector3(
wx + restitution * dx,
wy + restitution * dy,
0);
pj.velocity = new THREE.Vector3(
wx - restitution * dx,
wy - restitution * dy,
0);
// We can print the KE and momentum before and after to check
console.log("KE before ",
pi.velocity.lengthSq()+pj.velocity.lengthSq());
console.log("M before ",
pi.velocity.x+pj.velocity.x ,
pi.velocity.y+pj.velocity.y);
console.log("KE after",v1x*v1x+v1y*v1y + v2x*v2x + v2y*v2y);
console.log("M after ", v1x+v2x, v1y+v2y);
console.log("KE rest",
pi.velocity.lengthSq()+pj.velocity.lengthSq());
console.log("M rest ",
pi.velocity.x+pj.velocity.x ,
pi.velocity.y+pj.velocity.y);
This can simplify nicely. Start by taking the mean and half the difference of the two particles. Reflect the difference and apply the restitution
var len = pjmpi.length();
// unit vector normal to plane of collision
var nx = pjmpi.x / len;
var ny = pjmpi.y / len;
// unit vector tangent to plane of collision
var tx = -ny;
var ty = nx;
// center of mass
var wx = (pi.velocity.x+pj.velocity.x)/2;
var wy = (pi.velocity.y+pj.velocity.y)/2;
// half difference
var dx = (pi.velocity.x-pj.velocity.x)/2;
var dy = (pi.velocity.y-pj.velocity.y)/2;
// resolve in two directions
var a = dx * nx + dy * ny;
var b = dx * tx + dy * ty;
// reflect difference in normal
var cx = -a * nx + b * tx;
var cy = -a * ny + b * ty;
// apply restitution and add back center of mass
pi.velocity.set(
wx + restitution * cx,
wy + restitution * cy,
0);
pj.velocity.set(
wx - restitution * cx,
wy - restitution * cy,
0);
I've used THREE as little as possible to avoid creating too many objects.
I've saved this as a fiddle at http://jsfiddle.net/SalixAlba/8axnL59k/. I've reduced number of points, and removed gravity to make things a bit simpler to see.
Besides the very good points in the other answers, you only want to do the velocity changes if the particles move towards each other. This is the case of the derivative of the distance is negative, which can be transformed to the scalar product of pi-pj and vi-vj being negative.
Without that you may enter an infinite loop where the velocities get reflected back and forth while the distance stays below the critical radius.

I cannot get the same accuracy as Google maps when it comes to distance?

I am developing an app which calculate the distance between 2 points. I cannot use the Google Maps API.
I have found the coordinates for each of the markers in the map below.
I am then using the haversine formula to calculate the distance between each points.
e.g. 1 -> 2, 2 -> 3, 3 -> 4... etc up to the final point.
I add up these distances to retrieve the total distance for the route.
The problem is Google maps says it is 950-1000 meters, but my app says the length is 1150-1200 meters. I have tried adding in more coordinates, removing coordinates, but I am still getting approximately 200 meters longer route.
Out of curiosity I calculated the distance between the start and end point (the 2 green stars) and this matched the Google Maps distance (998 metres to be exact).
Does this mean Google Maps calculates its distances without the consideration of roads / paths etc.
Here is my code:
var coordinates = [
[1,51.465097,-3.170893,1,0],
[2,51.465526,-3.170714,0,0],
[3,51.465853,-3.170526,0,0],
[4,51.466168,-3.170338,0,0],
[5,51.466305,-3.170236,0,0],
[6,51.466534,-3.170157,0,0],
[7,51.466798,-3.170159,0,0],
[8,51.467042,-3.170232,0,0],
[9,51.467506,-3.170580,0,0],
[10,51.468076,-3.171532,0,0],
[11,51.468863,-3.172170,0,0],
[12,51.469284,-3.172841,0,0],
[13,51.469910,-3.174732,0,0],
[14,51.470037,-3.174930,0,0],
[15,51.470350,-3.175091,0,0],
[16,51.472447,-3.176151,1,0]
];
function distanceBetweenCoordinates() //calculates the distance between each of the coordinates
{
for (var i=0; i<coordinates.length-1; i++)
{
var firstClosestPoint = [0,0,6371];
var secondClosestPoint = [0,0,6371];
var lng1 = (coordinates[i][1]);
var lat1 = (coordinates[i][2]);
var lng2 = (coordinates[i+1][2]);
var lat2 = (coordinates[i+1][2]);
var d = haversine(lat1, lng1, lat2, lng2);
routeLength = routeLength + d;
}
return distanceBetweenCoordinatesArray; //returns the array which stores the 2 points and the distance between the 2 points
}
EDIT
Here is my haversine forumla to calculate the distance between 2 points:
Source: here
Number.prototype.toRad = function() //to rad function which is used by the haversine formula
{
return this * Math.PI / 180;
}
function haversine(lat1, lng1, lat2, lng2) { //haversine foruma which is used to calculate the distance between 2 coordinates
lon1 = lng1;
lon2 = lng2;
var R = 6371000; // metres
var a = lat1.toRad();
var b = lat2.toRad();
var c = (lat2-lat1).toRad();
var d = (lon2-lon1).toRad();
var a = Math.sin(c/2) * Math.sin(c/2) +
Math.cos(a) * Math.cos(b) *
Math.sin(d/2) * Math.sin(d/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d;
}
If I have correctly entered your start and end points, this implementation of the haversine formula (which I have tested in the real world) produces a distance of 895m (straight line).
var lt = 51.472447;
var lt1 = 51.465097;
var ln = -3.176151;
var ln1 = -3.170893;
var dLat = (lt - lt1) * Math.PI / 180;
var dLon = (ln - ln1) * Math.PI / 180;
var a = 0.5 - Math.cos(dLat) / 2 + Math.cos(lt1 * Math.PI / 180) * Math.cos(lt * Math.PI / 180) * (1 - Math.cos(dLon)) / 2;
d = Math.round(6371000 * 2 * Math.asin(Math.sqrt(a)));
$('#distance').html(d);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="distance"></div>

Use X,Y coordinates to plot points inside a circle

Is there a way in javascript to plot x,y coordinates so they fall into a circle rather than a square?
For example if I have the following code:
circleRadius = 100;
context.drawImage(img_elem, dx, dy, dw, dh);
I need to figure out a combination of x,y values that would fall inside a 100 pixel circle.
Thanks!
choose an x at random between -100 and 100
a circle is defined by x^2 + y^2 = r^2, which in your case equals 100^2 = 10000
From this equation you can get that y^2 = 10000 - x^2 , therefore the points with a chosen x and y = +/-sqrt(10000 - x^2) will lye on the circle.
choose an y at random between the two coordinates found at point 3
You're set!
EDIT:
In JS:
var radius = 100;
x = Math.random() * 2 * radius - radius;
ylim = Math.sqrt(radius * radius - x * x);
y = Math.random() * 2 * ylim - ylim;
Another edit: a jsFiddle Example
If you want equidistributed coordinates you better go for
var radius = 100
var center_x = 0
var center_y = 0
// ensure that p(r) ~ r instead of p(r) ~ constant
var r = radius*Math.sqrt(Math.random(1))
var angle = Math.sqrt(2*Math.PI)
// compute desired coordinates
var x = center_x + r*Math.cos(angle);
var y = center_y + r*Math.sin(angle);
If you want more points close to the middle then use
var r = radius*Math.random(1)
instead.
not sure what you mean for javascript but
x = R*cos(theta) and y = R*sin(theta) are the Cartesian points for a circle. R is the radius of course and theta is the angle which goes from 0 to 2*Pi.
I'm posting this as a solution because this question was the only relevant result in google.
My question/problem was how to add cartesian coordinates inside a circle where x and y would not exceed r.
Examples:
plot: (45,75) inside a circle with a radius of 100 (this would normally fall inside the circle, but not the correct position)
plot: (100,100) inside a circle with a radius of 100 (this would normally fall outside the circle
Solution
// The scale of the graph to determine position of plot
// I.E. If the graph visually uses 300px but the values only goto 100
var scale = 100;
// The actual px radius of the circle / width of the graph
var radiusGraph = 300;
// Plot the values on a cartesian plane / graph image
var xCart = xVal * radiusGraph;
var yCart = yVal * radiusGraph;
// Get the absolute values for comparison
var xCartAbs = Math.abs( xCart );
var yCartAbs = Math.abs( yCart );
// Get the radius of the cartesian plot
var radiusCart = Math.sqrt( xCart * xCart + yCart * yCart );
// Compare to decide which value is closer to the limit
// Once we know, calculate the largest possible radius with the graphs limit.
// r^2 = x^2 + y^2
if ( xCartAbs > yCartAbs ) { // Less than 45°
diff = scale / xCartAbs;
radiusMaximum = Math.sqrt( radiusGraph * radiusGraph + Math.pow( yCartAbs * diff, 2) );
} else if ( yCartAbs > xCartAbs ) { // Greater than 45°
diff = scale / yCartAbs;
radiusMaximum = Math.sqrt( radiusGraph * radiusGraph + Math.pow( xCartAbs * diff, 2) );
} else { // 45°
radiusMaximum = Math.sqrt( 2 * ( radiusGraph * radiusGraph ) );
}
// Get the percent of the maximum radius that the cartesian plot is at
var radiusDiff = radiusCart / radiusMaximum;
var radiusAdjusted = radiusGraph * radiusDiff;
// Calculate the angle of the cartesian plot
var theta = Math.atan2( yCart, xCart );
// Get the new x,y plot inside the circle using the adjust radius from above
var xCoord = radiusAdjusted * Math.cos( theta );
var yCoord = radiusAdjusted * Math.sin( theta );
Not sure if this is correct JavaScript code, but something like this:
for (x = -r; x < r; x++) {
for (y = -r; x < r; y++) {
if ((x * x + y * y) < (r * r)) {
// This x/y coordinate is inside the circle.
// Use <= if you want to count points _on_ the circle, too.
}
}
}

Categories