Math.sqrt one works one doesn't why? [duplicate] - java

This question already has answers here:
What does the ^ operator do in Java?
(19 answers)
Closed 4 years ago.
Add the following method to the Point class:
public double distance(Point other)
Returns the distance between the current Point object and the given other Point object. The distance between two points is equal to the square root of the sum of the squares of the differences of their x- and y-coordinates. In other words, the distance between two points (x1, y1) and (x2, y2) can be expressed as the square root of (x2 - x1)2 + (y2 - y1)2. Two points with the same (x, y) coordinates should return a distance of 0.0.
public class Point {
int x;
int y;
// // your code goes here
}
This works:
public double distance(Point other){
return Math.sqrt((this.x-other.x)*(this.x-other.x) + (this.y-other.y)*(this.y-other.y));
}
This doesn't:
public double distance(Point other){
return Math.sqrt((this.x-other.x)^2 + (this.y-other.y)^2);
}
May I ask why? TY

To get this out of the list of unanswered questions and because I think it is not a typo:
^ is not "power-of", it is XOR.

Related

Sorting by Polar Angle

I'm trying to implement the Graham’s Scan algorithm for a convex hull in Java, and have trouble sorting the points by polar angle with respect to the point with lowest y-value.
I have found this answer and understand how to calculate the polar angle but not how to sort the points.
I have seen implementations were Collections.sort() is being used but none of them seem to work with the Point2D class which I want to use because I want to be able to have doubles as coordinates.
Basically I want to be able to sort an ArrayList<Point2D> by their polar angle to the point with the lowest y-value in the same ArrayList.
Could someone please help me with this? Thanks.
I modified the last answer to this question.
Define a new class for Point:
class Point {
private long x, y;
Point(long x, long y) {
this.x = x;
this.y = y;
}
Point() {
x = 0;
y = 0;
}
public long getX() {
return x;
}
public long getY() {
return y;
}
}
Define a new function for calculating the cross product of two vectors:
public long cross(long x1, long y1, long x2, long y2) {
return x1 * y2 - x2 * y1;
}
Let's assume that initial is the Point which has the lowest Y coordinate. Also, let's assume that List<Point> points is a list with all the other points available, but it does NOT contain the initial point.
In order to sort the list, we can use Collections.sort with the comparator:
Collections.sort(points, (a, b) -> {
long cr = cross(a.getX() - initial.getX(), a.getY() - initial.getY(), b.getX() - initial.getX(), b.getY() - initial.getY());
if (cr > 0)
return 1;
else
return -1;
});
In this solution, we used the cross product to check whether two vectors are positioned clockwise or counter-clockwise.
This solution has two benefits:
It's more precious when our coordinates are integer numbers. When we calculate angles in other solutions, we may have some errors in floating point calculations.
In other solutions we may have "division by zero", but we don't have this problem here.
Let's assume that initial is the Point2D which has the lowest Y coordinate. Also, let's assume that List<Point2D> points is a list with all the other points available, but it does NOT contain the initial point.
In order to sort the list, we can use Collections.sort with the comparator:
Collections.sort(points, (a, b) -> {
double cotanA = -(a.getX() - initial.getX()) / (a.getY() - initial.getY());
double cotanB = -(b.getX() - initial.getX()) / (b.getY() - initial.getY());
if (cotanA - cotanB < 0) {
return 1;
}
return -1;
});
Edit:
This solution might encounter a division by zero. One way to overcome this is to use a cross product. See this answer from Erfan Alimohammadi.

Find points on triangle

I have 3 vertices of a triangle and I'm trying to find all the integer points that lie on the inside and ON THE SIDES of the triangle. I've tried numerous methods and they all succeed in finding the inside points, but fail in finding the points on the sides of the triangle. Currently I'm using barycentric coordinates:
private static boolean pointInTriangle(int[] p, int[] c1, int[] c2, int[] c3){
float alpha = ((c2[1] - c3[1])*(p[0] - c3[0]) + (c3[0] - c2[0])*(p[1] - c3[1])) /
((c2[1] - c3[1])*(c1[0] - c3[0]) + (c3[0] - c2[0])*(c1[1] - c3[1]));
float beta = ((c3[1] - c1[1])*(p[0] - c3[0]) + (c1[0] - c3[0])*(p[1] - c3[1])) /
((c2[1] - c3[1])*(c1[0] - c3[0]) + (c3[0] - c2[0])*(c1[1] - c3[1]));
float gamma = 1.0f - alpha - beta;
return ( (alpha>=0.0f) && (beta>=0.0f) && (gamma>=0.0f) );
For example, for vertices (0,0),(0,10),(10,10) this does find (10,8) but it also finds (11,8) which is not correct.
Can somebody help me?
Thanks in advance!
Use the code you alreay have to find if a position is inside the triangle. Then for the other part, if a point is on the line or not..
I would do it like this..
Check by calculating the distance between 2 vertices at a time.
Lets say we have vertices a, b and c. And the point p.
Check if p is on the line between a and b.
This can be done by measuring the distance between a -> p and p -> b.
If those two distances equals the distance of a -> b then it is on the line. If p should be off the line the distance will be longer.
Here is a method to caluclate distance (pythagoran teorem):
private static double GetDistance(double x1, double y1, double x2, double y2)
{
double a = Math.abs(x1-x2);
double b = Math.abs(y1-y2);
return Math.sqrt(a * a + b * b);
}

Point within and on circle [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have solved this problem but im not sure if its correct..
User should give the coordinates of a point and I should check if that point is within,outside or on the circle. I used the distance formula to solve this .
The given information about the circle are:
Circle is centered at ( 0,0 )
and radius is 10
public static void main(String[] strings) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a point with two coordinates");
double y1 = scanner.nextDouble();
double x1 = scanner.nextDouble();
// circle is centered at 0,0
double y2 = 0;
double x2 = 0;
double radius = 10;
double distance;
// using the distance formula to calculate the distance
// from the point given from the user and point where circle is centered
/**
* distance formula
* d = √ ( x2 - x1 )^2 + (y2 - y1 )^2
*/
distance = Math.pow( x2 - x1,2) + Math.pow(y2-y1,2);
// find square root
distance = Math.sqrt(distance);
String result="";
if(distance < radius) {
result = "("+y1+" , "+x1+")" +" is within the circle";
}
else if(distance > radius) {
result = y1+" , "+x1 +" is outside the circle";
}
else if(distance == radius) {
result =y1+" , "+x1 +" is on the circle";
}
System.out.println(result);
}
It's fine but sloppy.
There's no need to compute the square root. Work in units of distance squared.
Then compare using distance < radius * radius etc., perhaps renaming distance for the sake of clarity. Computing square roots is costly and imprecision can creep in which can be difficult to control. This is particularly important in your case where you want to test for a point being on the circle's edge.
Also consider writing (x2 - x1) * (x2 - x1) rather than using pow for the second power. Although Java possibly (I never remember for sure which is certainly a good enough reason for my not using it) optimises to the longer form, other languages (such as C) don't and imprecision can creep in there too.
Are you sure this question requires doubles as input? The examples given are integers. With integers you can be sure of a points location, with real numbers (doubles) you cannot be sure about the "on circle" or not which is another reason I think the question expects you to use integers.
And the trick for performance and accuracy is to not use Math.sqrt and only work with integers.
int x;
int y;
int centreX;
int centreY;
int deltaX = x - centreX;
int deltaY = y - centreY;
int distanceSquared = deltaX * deltaX + deltaY * deltaY;
int radiusSquared = radius * radius;
if (distanceSquared == radiusSquared) { //distance == radius
//on circle
} else if (distanceSquared < radiusSquared) { //distance < radius
//in circle
} else {
//out of circle
}
Consider using Math.hypot() to calculate a distance and compare double values using some small threshold:
static final double DELTA = 1E-5; // not necessarily 1E-5; see comments
//...
distance = Math.hypot(x2 - x1, y2 - y1);
if (Math.abs(distance - radius) < DELTA)
// on the circle
else if (distance > radius)
// outside
else
// inside
The reason for using DELTA is that there is a very small chance to get equal double values by calculations. If they differ in at least one bit, direct comparison will return false.
By appliying threshold, you check not whether the point lays exactly on the circle, but whether it lays inside a ring between radius - DELTA and radius + DELTA. So DELTA is a kind of tolerance limit which value should be chosen particularily for application, e. g. depending on absolute or relative input inaccuracy.

How to use OOP to branch from a point class into lines and triangles (Java) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to create simple objects, branching out from a single point object, into a line object (two points), and then into a triangle object (three points). I understood how to create the point class, though when trying to branch into the line class, I got a bit confused with how to actually go into writing a line class or triangle class using the initial point class. I need some help with going from a single point class into
I can post some code that I have done so far.
I also have read that there are already java geometry classes out there, but I want to actually create these classes to practice with OOP.
edit --- Added code below
class Point
{
private double x;
private double y;
public Point()
{
x = 0.0;
y = 0.0;
}
public Point(double x, double y)
{
this.x = x;
this.y = y;
}
public double getX()
{
return this.x;
}
public double getY()
{
return this.y;
}
public void setX(double x)
{
this.x = x;
}
public void setY(double y)
{
this.y = y;
}
public double distance(Point p)
{
return Math.sqrt((this.x - p.x) * (this.x - p.x) + (this.y - p.y)
* (this.y - p.y));
}
public String toString()
{
String s = "(" + x + ", " + y + ")";
return s;
}
public boolean equals(Point p)
{
double delta = 1.0e-18;
return (Math.abs(this.x - p.x) < delta)
&& (Math.abs(this.y - p.y) < delta);
}
//-----------------Line Class--------------------//
class Line
{
private Point p1;
private Point p2;
public Line()
{
p1 = new Point (0,0);
p2 = new Point (1,1);
}
public Line(double x1, double y1, double x2, double y2)
{
p1 = new Point (x1, y1);
p2 = new Point (x2, y2);
}
public Line(Point p, Point q)
{
p1 = new Point(p.getX(), p.getY());
p2 = new Point(q.getX(), q.getY());
}
public Point getP1()
{
return this.p1;
}
public Point getP2()
{
return this.p2;
}
public void setP1(double x, double y)
{
Point p1 = new Point(x, y);
this.p1 = p1;
}
public void setP2(double x, double y)
{
Point p2 = new Point(x, y);
this.p2 = p2;
}
public boolean isParallelY()
{
double delta = 1.0e-18;
return (Math.abs(p1.getX() - p2.getX()) < delta);
}
public boolean isParallelX()
{
double delta = 1.0e-18;
return (Math.abs(p1.getY() - p2.getY()) < delta);
}
public boolean isParallel (Line line)
{
if (this.Slope() == line.Slope())
return true;
else
return false;
}
public double Slope()
{
double inf = Double.POSITIVE_INFINITY;
if(isParallelY())
return inf;
return ((p2.getY() - p1.getY()) / (p2.getX() - p1.getX()));
}
public double xIntercept()
{
return -(p1.getY() / Slope() - p1.getX());
}
public double yIntercept()
{
return p1.getY() - (Slope() * p1.getX());
}
I am still adding methods to the line class right now and have not started on the triangle class (though I was thinking of creating a triangle with 3 points rather than 3 lines. And sorry about the branching confusion, I am relatively new.
A Line has 2 Points, so any Line class will have 2 Point-attributes
Any Triangle has 3 Points, so any Triangle class will have 3 Point-attributes
You can create the constructor of these classes to ensure correct objects.
public Line(Point point1, Point point2)
{
this.point1 = point1;
this.point2 = point2;
}
and for the Triangle class
public Triangle(Line line1, Line line2, Line line3)
{
this.point1 = line1.firstpoint();
this.point2 = line2.firstpoint();
this.point3 = line3.firstpoint();
}
or
public Triangle(Point point1, Point point2, Point point3)
{
this.point1 = point1;
this.point2 = point2;
this.point3 = point3;
}
Since each class contains the right attributes you can calculate with them.
If you really want to do OOP, think about what objects exist in your domain, and what messages they understand - that's all Mr Kay ever talked about :)
In your case, you've found Points. Seems you are thinking in a 2D point, and that's why you've just used x and y coordinates. In a 2D world, what would we like to ask to a Point? It's position/coordinates, right - we already have them. What else? A distance to another Point, right. That seems to be pretty much everything a Point can do by now.
Wait - we can ask it to join another Point, creating a Line. So, maybe, doing aPoint.lineTo(anotherPoint) isn't that bad. But, hey, the important thing is we are actually creating Lines.
They consist in a pair of dots. What would we like to ask to a Line? It's lenght, of course. It's clearly the same as the distance between its points. We can ask it the distance to a Point (some mathematicians already defined it, yeah). We can ask a Line if it's parallel with another one, or if they cross. We can ask it at which point they cross. We can ask the angle formed by two lines. And, then, again, we can ask it to join with a third point, to create a Triangle.
Then we'll have a convex shape, so new fun things as area, perimeter, internal angles, external angles.
Try to think of things, concepts and definitions, and implement them as simply as you can. Try to make code as nearly as possible to the colloquial definitions of the concepts it represents. And construct new abstractions based on the previous ones.
Besides all of this, there's one thing you shall not forget: programming is modeling. Models are abstractions. OOP is about using objects to model the portion of the reality we are interested in. If you don't define the scope of what things you wish to model (as this case is just an educational activity, with no real requirements), you can spend your hole life adding methods to your objects, without much sense. Think in advance what things you would like to be able to do with your Points, Lines, Triangles, etc, and limit yourself to them.
Happy hacking :)

To determine if a point lies on a line [duplicate]

This question already has answers here:
Check is a point (x,y) is between two points drawn on a straight line
(11 answers)
Closed 9 years ago.
I am trying to find if a particular point lies on a line. What I have tried is . I find the slope of the line .Then I find the slope of the point with the initial coordinates of the line, say x1 and y1. IF both the slopes are equal then the point lies on the line .But because I am using double or even with float I get values with five decimal places and the slope are never equal. the code is as follows.
line.slope == (yTouch-line.yTouch1)/(xTouch-line.xTouch1)
Hi I am not able to add a comment.Can you please tell me what is an error delta
Assume the coordinates of the point to be tested are (x,y)
If you know the equation (say y=mx+c) then just substitute x and y in and check for equality. eg is (3,1) on y=2x-5 ?
1 = 2(3)-5 = 1 so it is on the line
If you don't know the equation but have two points (x1,y1) and (x2,y2) then first calculate the slope m= (y2-y1)/(x2-x1) and then use the y-y1=m(x-x1) form of the equation of a line and check for equality again.
e.g. is the point (4,4) on the line thru (2,3) and (5,4) ?
m=(4-3)/(5-2)=1/3
the equation is y-3=(1/3)(x-2)
and ....well it isnt
Alternatively, just get a 14 year old in your country to explain it to you. In my experience 14 year olds (think they ) know everything !
Hey go with geometric terms,
If your points are (x1, y1) and (x2, y2), and you want to find the point (x3, y3) that is n units away from point 2:
d = sqrt((x2-x1)^2 + (y2 - y1)^2) #distance
r = n / d #segment ratio
x3 = r * x2 + (1 - r) * x1 #find point that divides the segment
y3 = r * y2 + (1 - r) * y1 #into the ratio (1-r):r
Here's link!
Here is solution
public static void checkForLineInaPoint(Double x1, Double y1, Double x2, Double y2)
{
Double m = getSlope(x1,y1,x2,y2);
Double c = getConstant(x1,y1,x2,y2,m);
Double x3= new Double(10.001);
Double y3= new Double(10.001);
if(checkPointLiesonLine(x3,y3,m,c))
System.out.print("Yes");
else
System.out.print("No");
}
private static boolean checkPointLiesonLine(Double x3, Double y3, Double m, Double c)
{
Double temp = m*x3+c;
return temp.compareTo(y3)==0;
}
private static Double getConstant(Double x1, Double y1, Double x2, Double y2, Double m)
{
return y1-m*x1;
}
private static Double getSlope(Double x1, Double y1, Double x2, Double y2)
{
return (y2-y1)/(x2-x1);
}

Categories