1

G'day! When I know the slope and y-intercept of a line, I need to calculate an x-value that is 1 unit out from the line. For example, if pointA = (4,5), and I set a line going from it with 0 slope (and therefore 5 as the y-intercept), then the x value I want would be 5. If the slope were undefined (vertical), then the x value would be 4. And so on.

So far, I calculate x as x = m(point[0]+1)-b. This doesn't work so well for vertical lines, however. This and this are similar, but I can't read C# for the first, and on the second one, I don't need to eliminate any possible points (yet).

Community
  • 1
  • 1
Fred Barclay
  • 834
  • 1
  • 13
  • 24

1 Answers1

3

This is kind of hitting a nail with a sledge hammer, but if you're going to be running into geometry problems often, I'd either write or find a Point/Vector class like

import math
class Vector():
    def __init__(self, x=0.0, y=0.0, z=0.0):
        self.x = x
        self.y = y
        self.z = z

    def __add__(self, other):
        self.x += other.x
        self.y += other.y
        self.z += other.z
        return self

    def __sub__(self, other):
        self.x -= other.x
        self.y -= other.y
        self.z -= other.z
        return self

    def dot(self, other):
        return self.x*other.x + self.y*other.y + self.z*other.z

    def cross(self, other):
        tempX = self.y*other.z - self.z*other.y
        tempY = self.z*other.x - solf.x*other.z
        tempZ = self.x*other.y - self.y*other.x
        return Vector(tempX, tempY, tempZ)

    def dist(self, other):
        return math.sqrt((self.x-other.x)**2 + (self.y-other.y)**2 + (self.z-other.z)**2)

    def unitVector(self):
        mag = self.dist(Vector())
        if mag != 0.0:
            return Vector(self.x * 1.0/mag, self.y * 1.0/mag, self.z * 1.0/mag)
        else:
            return Vector()

    def __repr__(self):
        return str([self.x, self.y, self.z])

Then you can do all kinds of stuff like find the vector by subtracting two points

>>> a = Vector(4,5,0)
>>> b = Vector(5,6,0)
>>> b - a
[1, 1, 0]

Or adding an arbitrary unit vector to a point to find a new point (which is the answer to your original question)

>>> a = Vector(4,5,0)
>>> direction = Vector(10, 1, 0).unitVector()
>>> a + direction
[4.995037190209989, 5.099503719020999, 0.0]

You can add more utilities, like allowing Vector/Scalar operations for scaling, etc.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218