我对三个数据点进行了线性拟合并获得了 1 西格玛不确定性线。现在我想生成 100k 数据点,均匀分布在 1 sigma 误差线(左侧的大三角形)之间,但我不知道如何才能做到这一点。这是我的代码
import matplotlib.pyplot as plt
import numpy as np
import math
from scipy.optimize import curve_fit
x = np.array([339.545772, 339.545781, 339.545803])
y = np.array([-0.430843, -0.43084 , -0.430842])
def line(x,m,c):
return m*x + c
popt, pcov = curve_fit(line,x,y)
slope = popt[0]
intercept = popt[1]
xx = np.array([326.0,343.0])
fit = line(xx,slope,intercept)
fit_plus1sigma = line(xx, slope + pcov[0,0]**0.5, intercept - pcov[1,1]**0.5)
fit_minus1sigma = line(xx, slope - pcov[0,0]**0.5, intercept + pcov[1,1]**0.5)
plt.plot(xx,fit,"C4",label="Linear fit")
plt.plot(xx,fit_plus1sigma,'g--',label=r'One sigma uncertainty')
plt.plot(xx,fit_minus1sigma,'g--')
plt.fill_between(xx, fit_plus1sigma, fit_minus1sigma, facecolor="gray", alpha=0.15)
在 NumPy 中有一个 Numpy random triangle function但是,我无法在我的案例中实现这一点,我什至不确定这是否是正确的方法。我感谢任何帮助。
最佳答案
您可以使用这个answer通过 Severin Pappadeux以三角形均匀采样。为此,您需要三角形的角点。
要查找线条相交的位置,您可以按照此 answer 操作通过 Norbu Tsering 。然后你只需要三角形的左上角和左下角坐标。
将所有这些放在一起,您可以像这样解决您的问题。
找到交点:
# Source: https://stackoverflow.com/a/42727584/5320601
def get_intersect(a1, a2, b1, b2):
"""
Returns the point of intersection of the lines passing through a2,a1 and b2,b1.
a1: [x, y] a point on the first line
a2: [x, y] another point on the first line
b1: [x, y] a point on the second line
b2: [x, y] another point on the second line
"""
s = np.vstack([a1, a2, b1, b2]) # s for stacked
h = np.hstack((s, np.ones((4, 1)))) # h for homogeneous
l1 = np.cross(h[0], h[1]) # get first line
l2 = np.cross(h[2], h[3]) # get second line
x, y, z = np.cross(l1, l2) # point of intersection
if z == 0: # lines are parallel
return (float('inf'), float('inf'))
return (x / z, y / z)
p1 = ((xx[0], fit_plus1sigma[0]), (xx[1], fit_plus1sigma[1]))
p2 = ((xx[0], fit_minus1sigma[0]), (xx[1], fit_minus1sigma[1]))
cross = get_intersect(p1[0], p1[1], p2[0], p2[1])
通过这种方式,您可以获得每条线上的两个点,以及需要从该三角形内采样的交点。
然后你可以采样你需要的点:
# Source: https://stackoverflow.com/a/47425047/5320601
def trisample(A, B, C):
"""
Given three vertices A, B, C,
sample point uniformly in the triangle
"""
r1 = random.random()
r2 = random.random()
s1 = math.sqrt(r1)
x = A[0] * (1.0 - s1) + B[0] * (1.0 - r2) * s1 + C[0] * r2 * s1
y = A[1] * (1.0 - s1) + B[1] * (1.0 - r2) * s1 + C[1] * r2 * s1
return (x, y)
points = []
for _ in range(100000):
points.append(trisample(p1[0], p2[0], cross))
1000 点的示例图片:
关于Python均匀随机数生成三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63396275/