Python:直线,Slope k已知,一点P1已知,长度P1P2已知,如何获得P2?

时间:2017-04-03 01:57:39

标签: python

对于一条直线,斜率k是已知的,一个点(x1,y1)是已知的,如何使用python得到另一个点(x2,y2)? 我知道计算的方法,但不知道使用python进行编码。

  1. (Y2-Y1)/(X2-X1)= K
  2. sqrt((x2-x1)^ 2 +(y2-y1)^ 2)= length
  3. 如果两个未知方程式,两个变量都有幂1,linalg-solve应该有效,但是现在2rd函数的幂是2,如何处理呢?

    我试着简化如下,但似乎我不能应用linalg-solve

    1. kx2-y2-kx1 + y1 = 0
    2. (y2-y1)^ 2 +(x2-x1)^ 2 = length ^ 2
    3. 补充: 感谢你的所有答案... Posh_Pumpkin的代码正是我想要的,以前我认为我需要应用我经常使用的linalg-solve。

      这是基于他的答案的测试代码:假设P1 =(1,1)p2 =(x,y),p1p2 = sqrt(2),k = 1,那么p2必须是=(2,2)

      import numpy as np
      import math
      k = 1
      d = math.sqrt(2)
      p1 = (1,1)
      r_sq = d**2 / (1 + k**2)
      r = math.sqrt(r_sq)
      p2 = (p1[0] + r, p1[1] + k*r)
      print(p2)
      

2 个答案:

答案 0 :(得分:0)

为什么要使用复杂的解决方案?我会在P1 = (0, 0)

的假设下接近它

假设P1位于原点,并且知道slope = k,您知道P2 = (r, k*r)为常数r。可以通过计算距离r来计算P1P2。既然你说你已经知道了距离,我们可以简单地做:

r^2 + (k*r)^2 = d^2

查找r。找到r后,您可以在P2时获得P1 = (0, 0)的坐标。因此,要查找实际坐标,您只需执行P2 = P1 + P2。检查以下内容:

import math

# Obviously assume k and d are known constants, and P1 is a known point
k = # given k
d = # given d
p1 = # (given x coord, given y coord)

r_sq = d**2 / (1 + k**2)
r = math.sqrt(r_sq)
p2 = (p1[0] + r, p1[1] + k*r)
print(p2)

如果你必须使用numpy,你应该告诉我们你的代码以及究竟令你烦恼的是什么。什么阻止您使用该模块,无论是错误还是意外行为?

答案 1 :(得分:0)

您可以使用基本触发来解决此问题。这是一般推导。

let p1 = (x1,y1) & p2 = (x2 = x1+d, y2 = y1+h), 
let L be the distance between p1 & p2 
* note for p1 & p2 such that x1 != x2 && y1 != y2, a triangle can be formed Ldh such that tan(theta) = h/d

h/d is the slope of the line (m) connecting points p1 & p2, so tan(theta) = m
 => theta = atan(m), from the law of sines ( sin(a)/A = sin(b)/B ) 
 => sin(90)/L = sin(atan(theta))/y2
 => y2 = L*sin( atan(theta) )

now get x from the point slope form of a line y= y1+m(x-x1) = (y-y1)/m +x1
so x2 = (y2-y1)/m + x1

这是用python表达的:

from math import sin,  atan
from random import randint

# This is the formula for (x2,y2) = p2
x = lambda y2, m, x1, y1: (y2 - y1)/float(m) + x1
y = lambda l, m, y1: l*sin( atan(m)  ) + y1

# p2 constraints ( x2 > x1, y2 > y1 or x2 > x1, y2 < y1 )
p1 =  [randint(1,1000),randint(1,1000)]
p2 =  [randint(p1[0],1001),randint(0,p1[1])]

# calculate distance between p1 & p2 (L), also calculate slope (m)
slope = lambda x1,y1,x2,y2: (y2-y1)/float(x2-x1)
dist  = lambda x1,y1,x2,y2: ( (y2-y1)**2 + (x2-x1)**2  )**(0.5)
L = dist(p1[0],p1[1],p2[0],p2[1])
m = slope(p1[0],p1[1],p2[0],p2[1])

#  now see if our functions for x & y yield p2
y2 = y(L,m,p1[1])
p_derived = [ x(y2,m,p1[0],p1[1]),y2  ]
print "p1: ",p1 , "p2 actual: ",p2, "p2 derived: ",p_derived

所以在这里我生成两个随机点p1和p2,并通过将我的派生结果与实际结果进行比较来验证p2是否可以从斜率,距离和p1计算出来。