Search⌘ K
AI Features

Cartesian Point Class

Explore how to implement the Cartesian Point class and use vector cross products to calculate the position of a point relative to a line segment. Understand the findPosition() method and how to work with coordinates and vectors in Java to solve geometric problems programmatically.

Introduction to the Cartesian system

Let’s dive into the discrete mathematical concept of vector space. In computer science, vectors represent a couple of things, such as lists of only rows or of rows and columns. Sometimes, we can place a vector point with two coordinates, x and y, and find the direction of the point concerning a line segment.

This algorithm is used in producing maps and directions, finding the area of polygons, and much more using vector cross products.

“How do we get the direction of a point on a map? Should we turn right or left? We can figure that out using the x- and y-coordinates: x for right, y for left. We can also move forward if that point lies on the same line.”

In geometry, three concepts are vital: point, line, and plane. To understand these concepts, let’s first see the illustration below.

Using the cross product for the position of points

Looking at the illustration, we can say that point C is on the left side of the line segment AB (moving from point A to B). Is there any formula to find that in vector space?

Yes, there is. We can use the vector cross product.

In our next Java program, let’s calculate the direction of C from line segment AB.

OnLeftSide
OnRightSide
OnSameLine
class PointClass{
double x,y;
}
//GetDirection
class Main{
public static void main(String[] args) {
PointClass a = new PointClass();
a.x = -4;
a.y = 3;
PointClass b = new PointClass();
b.x = 2;
b.y = -3;
PointClass c = new PointClass();
c.x = -5;
c.y = -3;
PointClass ba = new PointClass();
ba.x = b.x - a.x;
ba.y = b.y - a.y;
PointClass ca = new PointClass();
ca.x = c.x - a.x;
ca.y = c.y - a.y;
double crossProductsOfBAndC = (ba.y * ca.x) - (ba.x * ca.y);
if(crossProductsOfBAndC > 0){
System.out.println("The point C is on the left of line AB.");
} else if(crossProductsOfBAndC < 0){
System.out.println("The point C is on the right of line AB.");
} else {
System.out.println("The point C is on the same line of AB.");
}
}
}
Java code for figuring out the location of a point

Take a look at the output of the OnLeftSide.java file:

The point C is on the left of line AB.

Next, let’s change all the coordinates of C to negative values in the OnRightSide.java file:

The point C is on the right of line AB.

Next, let’s change the value of C to (0,-1) in the OnSameLine.java file:

The point C is on the same line of AB.
  • Lines 7–15: This code makes use of Java’s built-in PointClass class to initialize three points A, B, and C, in the Cartesian plane, represented by a, b, and c in the code.

  • Lines 16–21: Then, we take two vectors between these points, AB\overrightarrow{\rm AB} and AC\overrightarrow{\rm AC} ...