本文整理了一些数学公式的python代码展示,长期更新
1. 根据三点坐标计算夹角
import math
def cal_angle(point_1, point_2, point_3):
"""
根据三点坐标计算夹角
:param point_1: 点1坐标
:param point_2: 点2坐标
:param point_3: 点3坐标
:return: 返回三个角的夹角值
"""
a = math.sqrt((point_2[0] - point_3[0]) ** 2 + (point_2[1] - point_3[1]) ** 2)
b = math.sqrt((point_1[0] - point_3[0]) ** 2 + (point_1[1] - point_3[1]) ** 2)
c = math.sqrt((point_1[0] - point_2[0]) ** 2 + (point_1[1] - point_2[1]) ** 2)
if a == 0 or b == 0 or c == 0:
return []
angle_1 = math.degrees(math.acos((a * a - b * b - c * c) / (-2 * b * c)))
angle_2 = math.degrees(math.acos((b * b - a * a - c * c) / (-2 * a * c)))
angle_3 = math.degrees(math.acos((c * c - a * a - b * b) / (-2 * a * b)))
return angle_1, angle_2, angle_3
2. 计算a到b、c所构成的直线的距离
import math
def cal_distance(a, b, c):
"""
计算a到b、c所构成的直线的距离
:param a: 点a坐标
:param b: 点b坐标
:param c: 点c坐标
:return: 距离
"""
S1 = math.sqrt((b[0] - c[0]) ** 2 + (b[1] - c[1]) ** 2)
S2 = math.sqrt((a[0] - c[0]) ** 2 + (a[1] - c[1]) ** 2)
S3 = math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
P = (S1 + S2 + S3) / 2
S = math.sqrt(math.fabs(P * (P - S1) * (P - S2) * (P - S3)))
dis = 2 * S / S1
return dis
3. 计算A到B、C构成直线的垂足
def cal_foot_point(A, B, C):
"""
计算A到B、C构成直线的垂足
:param A: 点A坐标
:param B: 点B坐标
:param C: 点C坐标
:return: 垂足坐标
"""
k = -((B[0] - A[0]) * (C[0] - B[0]) + (B[1] - A[1]) * (C[1] - B[1])) / ((C[0] - B[0]) ** 2 + (C[1] - B[1]) ** 2)
x = round(k * (C[0] - B[0]) + B[0])
y = round(k * (C[1] - B[1]) + B[1])
return x, y
4. 通过垂足和直线上的另外两点计算直线外的垂直点的距离
import math
def get_distance(footPoint, point1, point2):
"""
通过垂足和直线上的另外两点计算直线外的垂直点的距离
:param footPoint: 垂足坐标
:param point1: 点1坐标
:param point2: 点2坐标
:return: 直线外能与点1、2构成直角且在过垂足的垂线上的点到这两点连线的距离
"""
return math.sqrt(math.sqrt((footPoint[0] - point1[0]) ** 2 + (footPoint[1] - point1[1]) ** 2) * math.sqrt(
(footPoint[0] - point2[0]) ** 2 + (footPoint[1] - point2[1]) ** 2))
5. 判断两个多边形是否相交
from shapely.geometry import Polygon
def if_intersects(box1, box2):
"""
判断两个多边形是否相交
:param box1: 多边形1
:param box2: 多边形2
:return: 是否相交
"""
poly1 = Polygon(box1).convex_hull
poly2 = Polygon(box2).convex_hull
return poly1.intersects(poly2)
6. 计算两条直线的交点坐标
def cal_line_intersection(p1, p2, p3, p4):
"""
计算两条直线的交点
:param p1: 点1
:param p2: 点2(与点1构成第1条直线)
:param p3: 点3
:param p4: 点4(与点3构成第2条直线)
:return: 交点坐标
"""
x = ((p1[0] * p2[1] - p1[1] * p2[0]) * (p3[0] - p4[0]) - (p1[0] - p2[0]) * (p3[0] * p4[1] - p3[1] * p4[0])) / (
(p1[0] - p2[0]) * (p3[1] - p4[1]) - (p1[1] - p2[1]) * (p3[0] - p4[0]))
y = ((p1[0] * p2[1] - p1[1] * p2[0]) * (p3[1] - p4[1]) - (p1[1] - p2[1]) * (p3[0] * p4[1] - p3[1] * p4[0])) / (
(p1[0] - p2[0]) * (p3[1] - p4[1]) - (p1[1] - p2[1]) * (p3[0] - p4[0]))
return x, y
7. 计算两经纬度点的距离
from geopy.distance import geodesic
distance = geodesic((40.17090730499467, 116.23760690616871), (40.17091615348095,116.2376069061687)).m
print(distance)