Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

numpy - Python Join any three given points using a curve

This problem is different than what already reported because I have limited information to join the points. I am trying to join three points using a curve. I don't have any other information to join the curves. I want and have to achieve this for any given points. An example of three points is given below:

Point1 = [19.616, 8.171] 
Point2 = [28.7, 5.727]
Point3 = [34.506, 0.012125]

My code is given below:

def curve_line(point1, point2):
    a = (point2[1] - point1[1])/(np.cosh(point2[0]) - np.cosh(point1[0]))
    b = point1[1] - a*np.sinh(point1[0])
    print(a,b,point1,point2)
    x = np.linspace(point1[0], point2[0],100)
    c = [b,  -a,  0.65636074, -0.05219088]
    y = a*np.cosh(x) + b 
    return x,y

x1,y1 = curve_line(point1, point2)
x2,y2 = curve_line(point2, point3)
plt.plot(x1,y1)
plt.plot(x2,y2) 

My actual output and expected output are given below:

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You do it exactly the same way as with a curve. If you have a function with 3 parameters and fit it to three points, you'll get an exact solution with the curve going through all 3 points (it boils down to solving 3 equations with 3 unknowns):

import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

x = np.array([ 1.92, 30, 34.21])
y = np.array([8.30, 5, 0.06])

def fun(x, a, b, c):
    return a * np.cosh(b * x )+ c

coef,_ = curve_fit(fun, x, y)

plt.plot(x, y, 'o', label='Original points')
plt.plot(np.linspace(x[0],x[-1]), fun(np.linspace(x[0],x[-1]), *coef), label=f'Model: %5.3f cosh(%4.2f x) + %4.2f' % tuple(coef) )
plt.legend()
plt.show()

enter image description here

In some cases you'll have to give some sensible starting values. These values can be obtained from a rough sketch of the curve, an online function graphing tool may be helpful in understanding the influence of the individual parameters.

Example:

x = np.array([ 19.616, 28.7, 34.506])
y = np.array([8.171, 5.727, 0.012125])
p0 = [-0.1, 0.5, 8]
coef,_ = curve_fit(fun, x, y, p0)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...