Storing and Using Straight Line Equations in Object-Oriented Design

data structuresgeometrymathobject-oriented-design

How to store a straight line (infinite length, not a line segment) efficiently?

This is not a duplication of How to represent a geometric line programmatically?, because the linked question is about 3D, and it does not answer the main problem reflected in this question.

Definition of a straight line:

This question is asking about the data structure, not user interface. I don't care about how the equation is defined or presented (because I'm not making a graphing calculator).

Basically, a straight line is an equation (not necessarily a function of x or y) that, when drawn on a rectangular coordinate system, results in an infinitely long line, of any inclination (slope), at any intercept (assuming that the floating point range is not exceeded).

Therefore, these are all valid straight line equations:

y = x
y = -2x
y = x + 3
y = 4x + 5
x = 6
y = 7

They all stand for a straight line, as shown in https://www.desmos.com/calculator/jnotvj4k7u

I am trying to create a type (class or a class hierarchy) (in Java, if language matters) that can represent any of these straight lines.

Possible uses of a straight line:

  • Used in an image, such as imageline in GD to draw a line that cuts the image (the inverted Y-axis is a minor problem irrelevant to this question). For example, the equation y = x can cut an image diagonally.
  • Stored in a file. The structure in the file should be same as that in code.
  • Implement the equals and hashCode methods that work for identical lines.
  • Evaluate the intersection point of two straight lines.
  • Evaluate the intersection point(s) of a straight line and, say, a quadratic equation (given double a, double b, double c for ax^2 + bx + c = 0) or a circle (given Point center and double radius)

My question

I have considered three possible methods, which will be listed as an answer below: https://softwareengineering.stackexchange.com/a/324229/234322

My question is, is there a fourth solution? Or, is there a way to minimize the disadvantages of these methods?

Best Answer

The equations can be all rewritten into form :

a*X + b*Y + c = 0

That means you can store three doubles a, b and c.

This doesn't have a problem in representing an arbitrary slope. You can also calculate slope as a/b (or b/a). Two lines are equal if there exists k where a1*k = a2, b1*k=b2, c1*k = c2.

Related Topic