Finding the intersection of two lines

孤人 提交于 2021-02-08 11:20:34

问题


I have two lines:

y = -1/3x + 4
y = 3x + 85

The intersection is at [24.3, 12.1].

I have a set of coordinates prepared:

points = [[1, 3], [4, 8], [25, 10], ... ]
#y = -1/3x + b
m_regr = -1/3
b_regr = 4
m_perp = 3 #(1 / m_regr * -1)    

distances = []
points.each do |pair|
  x1 = pair.first
  y2 = pair.last
  x2 = ((b_perp - b_regr / (m_regr - m_perp))
  y2 = ((m_regr * b_perp) / (m_perp * b_regr))/(m_regr - m_perp)
  distance = Math.hypot((y2 - y1), (x2 - x1))
  distances << distance
end

Is there a gem or some better method for this?

NOTE: THE ABOVE METHOD DOES NOT WORK. See my answer for a solution that works.


回答1:


What's wrong with using a little math?

If you have:

y = m1 x + b1
y = m2 x + b2

It's a simple system of linear equations.

If you solve them, your intersection is:

x = (b2 - b1)/(m1 - m2)
y = (m1 b2 - m2 b1)/(m1 - m2)



回答2:


For Future Googlers:

def solution k, l, m, n, p, q, r, s
  intrsc_x1 = m - k
  intrsc_y1 = n - l
  intrsc_x2 = r - p
  intrsc_y2 = s - q

  v1 = (-intrsc_y1 * (k - p) + intrsc_x1 * (l - q)) / (-intrsc_x2 * intrsc_y1 + intrsc_x1 * intrsc_y2);
  v2 = ( intrsc_x2 * (l - q) - intrsc_y2 * (k - p)) / (-intrsc_x2 * intrsc_y1 + intrsc_x1 * intrsc_y2);

  (v1 >= 0 && v1 <= 1 && v2 >= 0 && v2 <= 1) ? true : false
end

The simplest and cleanest way I've found on the internet.




回答3:


After much suffering and many different tries, I found a simple algebraic method here that not only works but is dramatically simplified.

distance = ((y - mx - b).abs / Math.sqrt(m**2 + 1))

where x and y are the coordinates for the known point.



来源:https://stackoverflow.com/questions/17756435/finding-the-intersection-of-two-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!