该链接是利用向量计算点到面的距离的原理
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
def pointToArea(point1, point2, point3, point4):
"""
描述:point4到point1, point2, point3所在面的距离
:param point1:数据框的行切片,三维
:param point2:
:param point3:
:param point4:
:return:点到面的距离
"""
# 设法向量(x,y,z)的x=1
x = 1 # 法向量的x坐标
p1 = point1.values # 转化为矩阵
p2 = point2.values
p3 = point3.values
p4 = point4.values
v12 = p1 - p2 # p1到p2的向量
v13 = p1 - p3 # p1到p2的向量
X = np.vstack((v12, v13)) # 把向量v12、v13合并为2*3矩阵
a = -X[:, 0] # a的系数
yz = np.matrix(X[:, 1:]).I.dot(a) # X的逆矩阵乘以a
y = yz[0, 0] # 法向量的y坐标
z = yz[0, 1] # 法向量的z坐标
n = np.array([x, y, z]) # 法向量
v41 = p4 - p1 # p4到p1的向量
return abs(v41.dot(n) / n.dot(n))
# 测试
if __name__ == '__main__':
# 初始化数据
df = pd.DataFrame([[2, 3, 1], [4, 1, 2], [6, 3, 7], [-5, -4, 8]], columns=['x', 'y', 'z'])
point1 = df.loc[0]
point2 = df.loc[1]
point3 = df.loc[2]
point4 = df.loc[3]
# 计算点到面的距离
s = pointToArea(point1, point2, point3, point4) # s=8.647058823529413
print("点到面的距离s: " + str(s))