I have made a class Location which allows to set, change a location (coordinates x,y , the limits are decided by xMin,xMax,yMin,yMax), to caluculate the distance between two points, and to get the direction from another location.
The direction is in degress (in [0,2pi]) from another location.
The direction goes from North (assuming that North is the pole oriented where there are higher coordinates), in clockwise order.
package TruckingCompany;
public class Location
{
private double x;
private double y;
private static final double xMax=1000.0;
private static final double xMin=-1000.0;
private static final double yMax=1000.0;
private static final double yMin=-1000.0;
public Location()
{
setX(0.0);
setY(0.0);
}
public Location(double x,double y)
{
setX(x);
setY(y);
}
public Location(Location location)
{
setX(location.getX());
setY(location.getY());
}
public void setX(double x)
{
if(x>=xMin && x<=xMax)
this.x=x;
}
public void setY(double y)
{
if(y>=yMin && y<=yMax)
this.y=y;
}
public void set(double x,double y)
{
setX(x);
setY(y);
}
public double getX()
{
return x;
}
public double getY()
{
return y;
}
public double getDistanceFrom(Location from)
{
double dx,dy;
dx=from.getX()-x;
dy=from.getY()-y;
return Math.sqrt(Math.pow(dx, 2.0)+Math.pow(dy, 2.0));
}
public double getDirectionFrom(Location from)
{
double dy=from.getY()-y;
double direction=Math.PI/4 - Math.asin (Math.toRadians(dy/getDistanceFrom(from)));
if(Double.isNaN(direction)==false)
{
if(from.getX()-x<0.0)
direction+=Math.PI/2;
if(dy<0.0)
direction+=Math.PI;
}
return direction;
}
@Override
public String toString()
{
return "(" + x + " , " + y + ")";
}
}
The problem is the the precision, for example I try to calculate the distance from these two locations:
Location l1,l2;
l1=new Location(0.0,0.0);
l2=new Location(300.0,300.0);
System.out.print(Math.toDegrees(l1.getDirectionFrom(l2)));
The problem is the precision: in this example it prints 44.29 degrees, it should be 45.0, why a so huge loss of precision?
You’re near 45 degrees, which means you’re going to be operating close to maxima and minima for some trig functions. I’d check the steps and see if you’re getting an intermediate result very close to 0.
Try replacing the call to pow with
dx*dxanddy*dy.Break this up with intermediate results.