如何计算一个python函数来计算/绘制点和曲线之间的最小距离?

时间:2018-02-28 11:02:18

标签: geometry curves python

 def ownpow(a, b):
        if a > 0:
            return a**b
        if a < 0:
            temp = abs(a)**b
            return -1*temp

    a= np.array([-1000,     1, -1000,    27, -1000,   125,   216,   343,   512,  729]) 

    for i in a:
        print(ownpow(i,(1/3.)))

显示计算距离明显错误的数字。有人能告诉我我的代码有什么问题吗?

1 个答案:

答案 0 :(得分:0)

我将问题从二维优化问题改为一维问题:

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import fmin_cobyla
P = (2487,1858)  
def f(x):  
    return (1.77425666496e-05 * x**3 + -0.125555135823 * x**2 + 296.656015233 * x + -232082.382985)
def objective(X):
    x,y = X 
    return np.sqrt((x - P[0])**2 + (y - P[1])**2)
def c1(X):
    x,y = X
    return f(x) - y
X = fmin_cobyla(objective, x0=[0.1, 0.01], cons=[c1])
print ("The minimum distance is {0:1.2f}".format(objective(X)))
v1 = np.array(P) - np.array(X)
v2 = np.array([1, 2.0 * X[0]])
print ("dot(v1, v2) = ",np.dot(v1, v2))
x = np.linspace(1000, 3000, 500000)
plt.plot(x, f(x), 'r-', label='f(x)')
plt.plot(P[0], P[1], 'bo', label='point')
plt.plot([P[0], X[0]], [P[1], X[1]], 'b-', label='shortest distance')
plt.plot([X[0], X[0] + 1], [X[1], X[1] + 2.0 * X[0]], 'g-', label='tangent')
plt.axis('equal')
plt.xlabel('x')
plt.ylabel('y')
plt.show()