I'm trying to do some advanced features with android maps and to do that I need to do some operations on vectors. Now - I read the answer from this and it gave me some hints and tips. However, there is a part which I don't understand. Please allow me to quote this:
Now that we have the ray with its start and end coordinates, the problem shifts from "is the point within the polygon" to "how often intersects the ray a polygon side". Therefor we can't just work with the polygon points as before (for the bounding box), now we need the actual sides. A side is always defined by two points.
side 1: (X1/Y1)-(X2/Y2) side 2:
(X2/Y2)-(X3/Y3) side 3:
(X3/Y3)-(X4/Y4)
So my understanding is that every side of the triangle is actually a vector. But how is it possible to substract 2 points? Let's say I got a triangle with 3 vertices: A(1,1) , B(2,2), C (1,3). So according to that, I have to do, for example, (1,1)-(2,2) in order to calculate one of the sides. The question is how to do it programatically in java/android? Below I'm attaching the code which I already developed:
/** Creating the containers for screen
* coordinates taken from geoPoints
*/
Point point1_screen = new Point();
Point point2_screen = new Point();
Point point3_screen = new Point();
/* Project them from the map to screen */
mapView.getProjection().toPixels(point1, point1_screen);
mapView.getProjection().toPixels(point2, point2_screen);
mapView.getProjection().toPixels(point3, point3_screen);
int xA = point1_screen.x;
int yA = point1_screen.y;
int xB = point2_screen.x;
int yB = point2_screen.y;
int xC = point3_screen.x;
int yC = point3_screen.y;
int[] xPointsArray = new int[3];
int[] yPointsArray = new int[3];
xPointsArray[0] = xA;
xPointsArray[1] = xB;
xPointsArray[2] = xC;
yPointsArray[0] = yA;
yPointsArray[1] = yB;
yPointsArray[2] = yC;
Arrays.sort(xPointsArray);
int xMin = xPointsArray[0];
int yMin = yPointsArray[0];
int xMax = xPointsArray[xPointsArray.length-1];
int yMax = xPointsArray[xPointsArray.length-1];
int e = (xMax - xMin) / 100; // for ray calcultions
int width = mapView.getWidth();
int height = mapView.getHeight();
if(pPoint.x < xMin || pPoint.x > xMax || pPoint.y > yMin || pPoint.y < yMax)
{
DisplayInfoMessage(pPoint.x + " < " + xMin + " AND " + pPoint.x + " > " + xMax + " || " + pPoint.y + " < " + yMin + " AND " + pPoint.y + " > " + yMax );
// DisplayInfoMessage("Minimum is: "+ yPointsArray[0] + " and the maximum is: "+ yPointsArray[xPointsArray.length-1]);
}
else
{
GeoPoint start_point = new GeoPoint(xMin - e, pPoint.y);
Point start_point_container = new Point();
mapView.getProjection().toPixels(start_point, start_point_container);
int a, b, c, tx, ty;
int d1, d2, hd;
int ix, iy;
float r;
// calculating vector for 1st line
tx = xB - xA;
ty = yB - yA;
// equation for 1st line
a = ty;
b = tx;
c = xA*a - yA*b;
// get distances from line for line 2
d1 = a*xB + b*yB + c;
d2 = a*pPoint.x + b*pPoint.y + c;
DisplayInfoMessage("You clicked inside the triangle!" + "TRIANGLE POINTS: A("+xA+","+yA+") B("+xB+","+yB+") C("+xC+","+yC+")");
}
The pPoint hold the coordinates of the point which user clicked. I hope that I explained my problem well enough. Can someone give me some help with that? Appreciated!
I'm not an Android developer, but I see that android.graphics.drawable.shapes.Shape lacks the contains() method found in java.awt.Shape. It appears you'll have to develop your own test, as suggested in the article you cited. In addition, you might want to look at crossing/winding number algorithms.
But how is it possible to subtract 2 points?
Subtraction of vectors is well defined, and easily implemented in Java. Given two points as vectors, the components of the difference represent the tangent (slope) of a line connecting the points. The example in the article implements this in the following lines:
//get tangent vector for line 1
tx = v1x2 - v1x1;
ty = v1y2 - v1y1;
The foundation for the approach shown is discussed further in Line and Segment Intersections.
Related
I'm making a plugin for a Minecraft server that will let a player select two locations (x1, z1 (first location): x2, z2 (second location)) and allow them to set this area in between the two points (rectangular/square) to randomaly teleport them anywhere in the given locations.
For the sake of simplicity, I will leave most of the code out and just give you the segment I'm having trouble with. Below, this code will (on the event that a player joins the server) teleport them inside that area.
I've setup some dummy data inside nextInt() so you can understand the math.
Location 1 (x1, z1): -424, 2888
Location 2 (x2, z2): 4248, 3016
Above are the locations in the proram segment below. (Think of "z" as "y" on a graph).
#EventHandler
public void onPlayerJoin(PlayerJoinEvent event){
Player player = event.getPlayer();
int x = 0, y = 0, z = 0;
Random randLocation = new Random();
player.sendMessage(ChatColor.RED + "TELEPORTING TO WASTELAND..");
x = randLocation.nextInt(((2888 - 424) + 1) + 424);
z = randLocation.nextInt(((4248 - 3016) + 1) + 3016);
Location location = player.getLocation();
location.setX(x);
location.setZ(z);
location.setY(player.getWorld().getHighestBlockAt(x, z).getY());
player.teleport(location);
}
The problem is, sometimes one (or maybe both) of the locations have a negative value. I have tried and tried different methods of coming up with these numbers but I am stumped.
QUESTION:
Is there anyway to make Java select a random number between 2 givens?
Example:
randomLocation.nextInt(x1, x2);
randomLocation.nextInt(z1, z2);
You have a mistake in the code determining the random coordinates:
x = randLocation.nextInt(((2888 - 424) + 1) + 424);
z = randLocation.nextInt(((4248 - 3016) + 1) + 3016);
You are using x1 and z1 to determine the new x location, when you should be using x1 and x2:
randX = randLocation.nextInt(Math.abs(x2-x1) + 1) + Math.min(x1,x2);
randZ = randLocation.nextInt(Math.abs(z2-z1) + 1) + Math.min(z1,z2);
x = randLocation.nextInt((2888 - 424) + 1) + 424;
z = randLocation.nextInt((4248 - 3016) + 1) + 3016;
One more thing: it should be like this: assuming x2>x1 and z2>z1
x = randLocation.nextInt((x2 - x1) + 1) + x1;
z = randLocation.nextInt((z2 - z1) + 1) + z1;
I'm programming a software renderer in Java, and am trying to use Z-buffering for the depth calculation of each pixel. However, it appears to work inconsistently. For example, with the Utah teapot example model, the handle will draw perhaps half depending on how I rotate it.
My z-buffer algorithm:
for(int i = 0; i < m_triangles.size(); i++)
{
if(triangleIsBackfacing(m_triangles.get(i))) continue; //Backface culling
for(int y = minY(m_triangles.get(i)); y < maxY(m_triangles.get(i)); y++)
{
if((y + getHeight()/2 < 0) || (y + getHeight()/2 >= getHeight())) continue; //getHeight/2 and getWidth/2 is for moving the model to the centre of the screen
for(int x = minX(m_triangles.get(i)); x < maxX(m_triangles.get(i)); x++)
{
if((x + getWidth()/2 < 0) || (x + getWidth()/2 >= getWidth())) continue;
rayOrigin = new Point2D(x, y);
if(pointWithinTriangle(m_triangles.get(i), rayOrigin))
{
zDepth = zValueOfPoint(m_triangles.get(i), rayOrigin);
if(zDepth > zbuffer[x + getWidth()/2][y + getHeight()/2])
{
zbuffer[x + getWidth()/2][y + getHeight()/2] = zDepth;
colour[x + getWidth()/2][y + getHeight()/2] = m_triangles.get(i).getColour();
g2.setColor(m_triangles.get(i).getColour());
drawDot(g2, rayOrigin);
}
}
}
}
}
Method for calculating the z value of a point, given a triangle and the ray origin:
private double zValueOfPoint(Triangle triangle, Point2D rayOrigin)
{
Vector3D surfaceNormal = getNormal(triangle);
double A = surfaceNormal.x;
double B = surfaceNormal.y;
double C = surfaceNormal.z;
double d = -(A * triangle.getV1().x + B * triangle.getV1().y + C * triangle.getV1().z);
double rayZ = -(A * rayOrigin.x + B * rayOrigin.y + d) / C;
return rayZ;
}
Method for calculating if the ray origin is within a projected triangle:
private boolean pointWithinTriangle(Triangle triangle, Point2D rayOrigin)
{
Vector2D v0 = new Vector2D(triangle.getV3().projectPoint(modelViewer), triangle.getV1().projectPoint(modelViewer));
Vector2D v1 = new Vector2D(triangle.getV2().projectPoint(modelViewer), triangle.getV1().projectPoint(modelViewer));
Vector2D v2 = new Vector2D(rayOrigin, triangle.getV1().projectPoint(modelViewer));
double d00 = v0.dotProduct(v0);
double d01 = v0.dotProduct(v1);
double d02 = v0.dotProduct(v2);
double d11 = v1.dotProduct(v1);
double d12 = v1.dotProduct(v2);
double invDenom = 1.0 / (d00 * d11 - d01 * d01);
double u = (d11 * d02 - d01 * d12) * invDenom;
double v = (d00 * d12 - d01 * d02) * invDenom;
// Check if point is in triangle
if((u >= 0) && (v >= 0) && ((u + v) <= 1))
{
return true;
}
return false;
}
Method for calculating surface normal of a triangle:
private Vector3D getNormal(Triangle triangle)
{
Vector3D v1 = new Vector3D(triangle.getV1(), triangle.getV2());
Vector3D v2 = new Vector3D(triangle.getV3(), triangle.getV2());
return v1.crossProduct(v2);
}
Example of the incorrectly drawn teapot:
What am I doing wrong? I feel like it must be some small thing. Given that the triangles draw at all, I doubt it's the pointWithinTriangle method. Backface culling also appears to work correctly, so I doubt it's that. The most likely culprit to me is the zValueOfPoint method, but I don't know enough to know what's wrong with it.
My zValueOfPoint method was not working correctly. I'm unsure why :( however, I changed to a slightly different method of calculating the value of a point in a plane, found here: http://forum.devmaster.net/t/interpolation-on-a-3d-triangle-using-normals/20610/5
To make the answer here complete, we have the equation of a plane:
A * x + B * y + C * z + D = 0
Where A, B, and C are the surface normal x/y/z values, and D is -(Ax0 + By0 + Cz0).
x0, y0, and z0 are taken from one of the vertices of the triangle. x, y, and z are the coordinates of the point where the ray intersects the plane. x and y are known values (rayOrigin.x, rayOrigin.y) but z is the depth which we need to calculate. From the above equation we derive:
z = -A / C * x - B / C * y - D
Then, copied from the above link, we do:
"Note that for every step in the x-direction, z increments by -A / C, and likewise it increments by -B / C for every step in the y-direction.
So these are the gradients we're looking for to perform linear interpolation. In the plane equation (A, B, C) is the normal vector of the plane.
It can easily be computed with a cross product.
Now that we have the gradients, let's call them dz/dx (which is -A / C) and dz/dy (which is -B / C), we can easily compute z everywhere on the triangle.
We know the z value in all three vertex positions.
Let's call the one of the first vertex z0, and it's position coordinates (x0, y0). Then a generic z value of a point (x, y) can be computed as:"
z = z0 + dz/dx * (x - x0) + dz/dy * (y - y0)
This found the Z value correctly and fixed my code. The new zValueOfPoint method is:
private double zValueOfPoint(Triangle triangle, Point2D rayOrigin)
{
Vector3D surfaceNormal = getNormal(triangle);
double A = surfaceNormal.x;
double B = surfaceNormal.y;
double C = surfaceNormal.z;
double dzdx = -A / C;
double dzdy = -B / C;
double rayZ = triangle.getV1().z * modelViewer.getModelScale() + dzdx * (rayOrigin.x - triangle.getV1().projectPoint(modelViewer).x) + dzdy * (rayOrigin.y - triangle.getV1().projectPoint(modelViewer).y);
return rayZ;
}
We can optimize this by only calculating most of it once, and then adding dz/dx to get the z value for the next pixel, or dz/dy for the pixel below (with the y-axis going down). This means that we cut down on calculations per polygon significantly.
this must be really slow
so much redundant computations per iteration/pixel just to iterate its coordinates. You should compute the 3 projected vertexes and iterate between them instead look here:
triangle/convex polygon rasterization
I dislike your zValueOfPoint function
can not find any use of x,y coordinates from the main loops in it so how it can compute the Z value correctly ?
Or it just computes the average Z value per whole triangle ? or am I missing something? (not a JAVA coder myself) in anyway it seems that this is your main problem.
if you Z-value is wrongly computed then Z-Buffer can not work properly. To test that look at the depth buffer as image after rendering if it is not shaded teapot but some incoherent or constant mess instead then it is clear ...
Z buffer implementation
That looks OK
[Hints]
You have too much times terms like x + getWidth()/2 why not compute them just once to some variable? I know modern compilers should do it anyway but the code would be also more readable and shorter... at least for me
I'm looking for some assistance with solving the below equations in Java
(a-x1)^2 + (b-y1)^2 = r1^2 + r^2
(a-x2)^2 + (b-y2)^2 = r2^2 + r^2
(a-x3)^2 + (b-y3)^2 = r3^2 + r^2
Values of x1, y1, r1, x2, y2, r2 & x3, y3, r3 are known.
I need to solve for a, b, r
How to go about doing this in Java? I checked the Commons Maths library but didn't find how I could achieve this. It helps with linear equations though.
I think you need linear equations for Gaussian elimination.
If a, b, and r are what you need to solve for, it's obvious that these are non-linear equations.
You'll need a non-linear solver, like Newton-Raphson.
You'll have to linearize your equations. Calculate the Jacobean for the differentials da, db, and dr.
You'll start with an initial guess
a = a(old)
b = b(old)
r = r(old)
use a linearized version of the equations to calculate an increment
2*(a(old)-x1)*da + 2*(b(old)-y1)*db = 2*r(old)*dr
2*(a(old)-x2)*da + 2*(b(old)-y2)*db = 2*r(old)*dr
2*(a(old)-x3)*da + 2*(b(old)-y3)*db = 2*r(old)*dr
update your guess
a(new) = a(old) + da
b(new) = b(old) + db
r(new) = r(old) + dr
and repeat until it converges (if it converges).
You should never solve linear equations using Gaussian elimination: it suffers from a number of problems. A better idea is to do LU decomposition and forward-back substitution.
If my linearized equations are correct, they take the form A(dx) = 0. What should the boundary condition be?
(a, b) are the coordinates for the center of the circle; r is the radius.
Do you really have three points (x1, y1), (x2, y2), and (x3, y3)? Or do you have lots more points? If it's the latter, you'll need a least squares fit.
hope this method can give you some ideas:
public int[] getCoordinates(float XR_1, float YR_1, float XR_2, float YR_2,
float XR_3, float YR_3, int R1, int R2, int R3) {
//define the positions
int XU_1 = 0, YU_1 = 0, XU_2 = 0, YU_2 = 0, XU, YU;
//define variables and arrays that needed
float D0[][] = new float[17][50];
float D1[][] = new float[17][50];
float f[][] = new float[17][50];
float fmin_1 = 0;
float fmin_2 = 0;
//define columns and rows
int i, j;
//Y goes from 0 to 49
for(j=0; j<=49; j++){
//X goes from 0 to 16
for(i=0; i<=16; i++){
D0[i][j] = (float) (Math.pow((i-XR_1),2) + Math.pow((j-YR_1),2) - Math.pow(R1,2));
D1[i][j] = (float) (Math.pow((i-XR_2),2) + Math.pow((j-YR_2),2) - Math.pow(R2,2));
f[i][j] = (float) Math.sqrt(Math.pow(D0[i][j], 2) + Math.pow(D1[i][j], 2));
//get two position where f[i][j] are the minimum
//initialise the minimum two positions
if(i==0 & j==0){
fmin_1 = f[i][j];
XU_1 = i;
YU_1 = j;
}
else if(j==0 & i==1){
if(f[i][j] < fmin_1){
fmin_2 = fmin_1;
fmin_1 = f[i][j];
XU_2 = XU_1;
XU_1 = i;
YU_2 = YU_1;
YU_1 = j;
}
else {
fmin_2 = f[i][j];
XU_2 = i;
YU_2 = j;
}
}
else{
if(f[i][j] < fmin_1){
fmin_2 = fmin_1;
fmin_1 = f[i][j];
XU_2 = XU_1;
XU_1 = i;
YU_2 = YU_1;
YU_1 = j;
}
else if(f[i][j] < fmin_2){
fmin_2 = f[i][j];
XU_2 = i;
YU_2 = j;
}
}
}
}
this method gives two closest points in the coordinate system, you can use the similar way to get the most ideal one.
I'm completely stuck.
I have an ellipse, and a line. Line is set by two points, ellipse - by bottom-left and top-right corners. I have to find their points of intersection, using java.
I tried to solve an equation system:
(1) y = kx + m;
x^2/a^2 + y^2/b^2 = 1;
but I could't make things work properly. I assume it's because of java's coordinate system, but it also may be my own mistake somewherem beacuse I'm confused with it.
Is there any better way to find points of intersection and, if not, how can I get them properly?
Thank you in advance.
Code:
double r1 = in_y2-in_y;
double r2 = in_x2-in_x;
double k = r1/r2;
double m = in_y2 - k*in_x2;
double a = Math.abs((double)x2 - (double)x)/2;
double b = Math.abs((double)y2 - (double)y)/2;
double A1 = 1/(a*a) + (k*k)/(b*b);
double B1 = (2*k*m)/b*b;
double C1 = (m*m)/(b*b);
double D = Math.sqrt(B1*B1 - 4*A1*C1);
double ex1 = (-B1 + D/(2*A1));
double ey1 = k*ex1 + m;
double ex2 = (-B1 - D/(2*A1));
double ey2 = k*ex2 + m;
This is probably no longer relevant to the original problem owner, but since I encountered the same question, let me present my answer.
There are three mistakes in the original computation that I can see: (i) the one pointed out by #mprivat, (ii) the bracketing in the assignment to B1 which should instead be
double B1 = (2*k*m)/(b*b);
and (iii) a more fundamental one: the presented computation does not correct for the origin of the ellipse. Since the ellipse is defined by itse circumscribing bounds, there is no guarantee that it is centered on (0,0).
Let's call the center (cx,cy), then the equation for the ellipse becomes
(x-cx)^2/a^2 + (y-cy)^2/b^2 = 1
rather than the original
x^2/a^2 + y^2/b^2 = 1
The simple repair, I think, is to translate the line wrt (cx,cy) and translate the results back, like so:
...
double m = (in_y2-cy) - k*(in_x2-cx);
...
double ex1 = (-B1 + D/(2*A1)) + cx;
double ey1 = k*(ex1-cx) + m + cy;
double ex2 = (-B1 - D/(2*A1)) + cx;
double ey2 = k*(ex2-cx) + m + cy;
The more elegant repair is to solve the correct equation for the ellipse instead, but this results in even more impenetrable formulas for B1 and C1:
double B1 = (2*k*(m-cy))/(b*b) - (2*cx)/(a*a);
double C1 = (m-cy)*(m-cy)/(b*b) - 1 + (cx*cx)/(a*a);
As a final remark, note that this breaks down for vertical lines, as then r2 = 0 so k isn't defined.
Java can't solve the algebra problem, but it can compute the solution once you tell it what to compute.
Sounds like you just need to replace your y in the ellipse's equation with kx+m then solve for x. Looks like it's a simply binomial equation. Write a program that computes x=... based on k, m, a and b. Java can help you compute the roots if you tell it what to compute and what the values of k, m, a and b are.
In your particular case, you want to use Java as a simple calculator...
can you please put your code so that we could see if it's correct?
anyway , here's an algorithm:
http://mathworld.wolfram.com/Ellipse-LineIntersection.html
note that since it has a square root , you might get a solution that is not precise.
Line2D.Double line = new Line2D.Double(x1,y1,x2,y2);
Ellipse2D.Double ellipse = new Ellipse2D.Double(x,y,width,height);
int resolution = 1000;
int x_distance = ellipse.getWidth()/2;
int y_distance = ellipse.getHeight()/2;
double angle = 360.0/(double)resolution;
Point center = new Point(width/2,height/2);
Point point = new Point();
for (int index = 0; index < resolution; index++)
{
int x = (center.x+x_distance)*Math.sin(Math.toRadians(angle*index)));
int y = (center.y+y_distance)*Math.cos(Math.toRadians(angle*index)));
Ellipse2D.Double dot = new Ellipse2D.Double(x,y,1,1);
if (line.intersects(dot.getBounds()))
{
point.setLocation(x,y);
index = resolution;
}
}
So apparently calculating square roots is not very efficient, which leaves me wondering what the best way is to find out the distance (which I've called range below) between two circles is?
So normally I would work out:
a^2 + b^2 = c^2
dy^2 + dx^2 = h^2
dy^2 + dx^2 = (r1 + r2 + range)^2
(dy^2 + dx^2)^0.5 = r1 + r2 + range
range = (dy^2 + dx^2)^0.5 - r1 - r2
Trying to avoid the square root works fine when you just look for the situation when "range" is 0 for collisions:
if ( (r1 + r2 + 0 )^2 > (dy^2 + dx^2) )
But if I'm trying to work out that range distance, I end up with some unwieldy equation like:
range(range + 2r1 + 2r2) = dy^2 + dx^2 - (r1^2 + r2^2 + 2r1r2)
which isn't going anywhere. At least I don't know how to solve it for range from here...
The obvious answer then is trignometry and first find theta:
Tan(theta) = dy/dx
theta = dy/dx * Tan^-1
Then the find the hypotemuse
Sin(theta) = dy/h
h = dy/Sin(theta)
Finally work out the range
range + r1 + r2 = dy/Sin(theta)
range = dy/Sin(theta) - r1 - r2
So that's what I've done and have got a method that looks like this:
private int findRangeToTarget(ShipEntity ship, CircularEntity target){
//get the relevant locations
double shipX = ship.getX();
double shipY = ship.getY();
double targetX = target.getX();
double targetY = target.getY();
int shipRadius = ship.getRadius();
int targetRadius = target.getRadius();
//get the difference in locations:
double dX = shipX - targetX;
double dY = shipY - targetY;
// find angle
double theta = Math.atan( ( dY / dX ) );
// find length of line ship centre - target centre
double hypotemuse = dY / Math.sin(theta);
// finally range between ship/target is:
int range = (int) (hypotemuse - shipRadius - targetRadius);
return range;
}
So my question is, is using tan and sin more efficient than finding a square root?
I might be able to refactor some of my code to get the theta value from another method (where I have to work it out) would that be worth doing?
Or is there another way altogether?
Please excuse me if I'm asking the obvious, or making any elementary mistakes, it's been a long time since I've used high school maths to do anything...
Any tips or advice welcome!
****EDIT****
Specifically I'm trying to create a "scanner" device in a game that detects when enemies/obstacles are approaching/ going away etc. The scanner will relay this information via an audio tone or a graphical bar or something. Therefore although I don't need exact numbers, ideally I would like to know:
target is closer/further than before
target A is closer/further than target B, C, D...
A (linear hopefully?) ratio that expresses how far a target is from the ship relative to 0 (collision) and max range (some constant)
some targets will be very large (planets?) so I need to take radius into account
I'm hopeful that there is some clever optimisation/approximation possible (dx + dy + (longer of dx, dy?), but with all these requirements, maybe not...
Math.hypot is designed to get faster, more accurate calculations of the form sqrt(x^2 + y^2). So this should be just
return Math.hypot(x1 - x2, y1 - y2) - r1 - r2;
I can't imagine any code that would be simpler than this, nor faster.
If you really need the accurate distance, then you can't really avoid the square root. Trigonometric functions are at least as bad as square root calculations, if not worse.
But if you need only approximate distances, or if you need only relative distances for various combinations of circles, then there are definitely things you can do. For example, if you need only relative distances, note that squared numbers have the same greater-than relationship as do their square roots. If you're only comparing different pairs, skip the square root step and you'll get the same answer.
If you only need approximate distances, then you might consider that h is roughly equal to the longer adjacent side. This approximation is never off by more than a factor of two. Or you could use lookup tables for the trigonometric functions -- which are more practical than lookup tables for arbitrary square roots.
I tired working out whether firstly the answers when we use tan, sine is same as when we use sqrt functions.
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
double shipX = 5;
double shipY = 5;
double targetX = 1;
double targetY = 1;
int shipRadius = 2;
int targetRadius = 1;
//get the difference in locations:
double dX = shipX - targetX;
double dY = shipY - targetY;
// find angle
double theta = Math.toDegrees(Math.atan( ( dY / dX ) ));
// find length of line ship centre - target centre
double hypotemuse = dY / Math.sin(theta);
System.out.println(hypotemuse);
// finally range between ship/target is:
float range = (float) (hypotemuse - shipRadius - targetRadius);
System.out.println(range);
hypotemuse = Math.sqrt(Math.pow(dX,2) + Math.pow(dY,2));
System.out.println(hypotemuse);
range = (float) (hypotemuse - shipRadius - targetRadius);
System.out.println(range);
}
The answer which i got was :
4.700885452542996
1.7008854
5.656854249492381
2.6568542
Now there seems a difference between the value with sqrt ones being more correct.
talking abt the performance :
Consider your code snippet :
i calculated the time of performance- which comes out as:
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
long lStartTime = new Date().getTime(); //start time
double shipX = 555;
double shipY = 555;
double targetX = 11;
double targetY = 11;
int shipRadius = 26;
int targetRadius = 3;
//get the difference in locations:
double dX = shipX - targetX;
double dY = shipY - targetY;
// find angle
double theta = Math.toDegrees(Math.atan( ( dY / dX ) ));
// find length of line ship centre - target centre
double hypotemuse = dY / Math.sin(theta);
System.out.println(hypotemuse);
// finally range between ship/target is:
float range = (float) (hypotemuse - shipRadius - targetRadius);
System.out.println(range);
long lEndTime = new Date().getTime(); //end time
long difference = lEndTime - lStartTime; //check different
System.out.println("Elapsed milliseconds: " + difference);
}
Answer - 639.3204215458475,
610.32043,
Elapsed milliseconds: 2
And when we try out with sqrt root one:
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
long lStartTime = new Date().getTime(); //start time
double shipX = 555;
double shipY = 555;
double targetX = 11;
double targetY = 11;
int shipRadius = 26;
int targetRadius = 3;
//get the difference in locations:
double dX = shipX - targetX;
double dY = shipY - targetY;
// find angle
double theta = Math.toDegrees(Math.atan( ( dY / dX ) ));
// find length of line ship centre - target centre
double hypotemuse = Math.sqrt(Math.pow(dX,2) + Math.pow(dY,2));
System.out.println(hypotemuse);
float range = (float) (hypotemuse - shipRadius - targetRadius);
System.out.println(range);
long lEndTime = new Date().getTime(); //end time
long difference = lEndTime - lStartTime; //check different
System.out.println("Elapsed milliseconds: " + difference);
}
Answer -
769.3321779309637,
740.33215,
Elapsed milliseconds: 1
Now if we check for the difference the difference between the two answer is also huge.
hence i would say that if you making a game more accurate the data would be more fun it shall be for the user.
The problem usually brought up with sqrt in "hard" geometry software is not its performance, but the loss of precision that comes with it. In your case, sqrt fits the bill nicely.
If you find that sqrt really brings performance penalties - you know, optimize only when needed - you can try with a linear approximation.
f(x) ~ f(X0) + f'(x0) * (x - x0)
sqrt(x) ~ sqrt(x0) + 1/(2*sqrt(x0)) * (x - x0)
So, you compute a lookup table (LUT) for sqrt and, given x, uses the nearest x0. Of course, that limits your possible ranges, when you should fallback to regular computing. Now, some code.
class MyMath{
private static double[] lut;
private static final LUT_SIZE = 101;
static {
lut = new double[LUT_SIZE];
for (int i=0; i < LUT_SIZE; i++){
lut[i] = Math.sqrt(i);
}
}
public static double sqrt(final double x){
int i = Math.round(x);
if (i < 0)
throw new ArithmeticException("Invalid argument for sqrt: x < 0");
else if (i >= LUT_SIZE)
return Math.sqrt(x);
else
return lut[i] + 1.0/(2*lut[i]) * (x - i);
}
}
(I didn't test this code, please forgive and correct any errors)
Also, after writing this all, probably there is already some approximate, efficient, alternative Math library out there. You should look for it, but only if you find that performance is really necessary.