2013-10-06 51 views
5

這看起來很簡單,但我無法弄清楚。我有一個從x,y數據計算出來的曲線。然後我有一條線。我想找到兩個相交處的x,y值。找到polyfit的曲線的交點

這是我到目前爲止。這是超級混亂,並沒有給出正確的結果。我可以查看圖表並找到交點x值並計算出正確的y值。我想刪除這個人的一步。

import numpy as np 
import matplotlib.pyplot as plt 
from pylab import * 
from scipy import linalg 
import sys 
import scipy.interpolate as interpolate 
import scipy.optimize as optimize 

w = np.array([0.0, 11.11111111111111, 22.22222222222222, 33.333333333333336, 44.44444444444444, 55.55555555555556, 66.66666666666667, 77.77777777777777, 88.88888888888889, 100.0]) 
v = np.array([0.0, 8.333333333333332, 16.666666666666664, 25.0, 36.11111111111111, 47.22222222222222, 58.333333333333336, 72.22222222222221, 86.11111111111111, 100.0]) 

z = np.polyfit(w, v, 2) 
print (z) 
p=np.poly1d(z) 
g = np.polyval(z,w) 
print (g) 
N=100 
a=arange(N) 
b=(w,v) 
b=np.array(b) 
c=(w,g) 
c=np.array(c) 
print(c) 
d=-a+99 
e=(a,d) 
print (e) 
p1=interpolate.PiecewisePolynomial(w,v[:,np.newaxis]) 
p2=interpolate.PiecewisePolynomial(w,d[:,np.newaxis]) 

def pdiff(x): 
    return p1(x)-p2(x) 

xs=np.r_[w,w] 
xs.sort() 
x_min=xs.min() 
x_max=xs.max() 
x_mid=xs[:-1]+np.diff(xs)/2 
roots=set() 
for val in x_mid: 
    root,infodict,ier,mesg = optimize.fsolve(pdiff,val,full_output=True) 
    # ier==1 indicates a root has been found 
    if ier==1 and x_min<root<x_max: 
     roots.add(root[0]) 
roots=list(roots)   
print(np.column_stack((roots,p1(roots),p2(roots)))) 

plt.plot(w,v, 'r', a, -a+99, 'b-') 
plt.show() 
q=input("what is the intersection value? ") 
print (p(q)) 

任何想法得到這個工作?

感謝

回答

5

我不認爲我完全理解你正在嘗試在代碼中做些什麼,而你用英語描述可以

from __future__ import division 
import numpy as np 
import matplotlib.pyplot as plt 

w = np.array([0.0, 11.11111111111111, 22.22222222222222, 33.333333333333336, 
       44.44444444444444, 55.55555555555556, 66.66666666666667, 
       77.77777777777777, 88.88888888888889, 100.0]) 
v = np.array([0.0, 8.333333333333332, 16.666666666666664, 25.0, 
       36.11111111111111, 47.22222222222222, 58.333333333333336, 
       72.22222222222221, 86.11111111111111, 100.0]) 

poly_coeff = np.polynomial.polynomial.polyfit(w, v, 2) 
poly = np.polynomial.polynomial.Polynomial(poly_coeff) 
roots = np.polynomial.polynomial.polyroots(poly_coeff - [99, -1, 0]) 

x = np.linspace(np.min(roots) - 50, np.max(roots) + 50, num=1000) 
plt.plot(x, poly(x), 'r-') 
plt.plot(x, 99 - x, 'b-') 
for root in roots: 
    plt.plot(root, 99 - root, 'ro') 

enter image description here

+1

公平的警告來完成,'np.polynomial.polynomial.polyfit'將係數'[A,B,C]'返回到'A + Bx + Cx^2 + ...',這與'np.polyfit'的順序相反你最初使用過,@ user2843767)返回:'... + Ax^2 + Bx + C'。不確定是誰做出這個決定,只是不採取第一個輸出,並在'np.poly1d'或np.polyval中使用它,除非你也使用'np.polyfit'。 – askewchan

+0

確實是公正的警告。沒有棄用警告,並且可能永遠不會存在,但是文檔[明確](http://docs.scipy.org/doc/numpy/reference/routines.polynomials.html)指出了新代碼的使用方式是Polynomial包,而不是舊的poly1d。 – Jaime

+0

是的,幸運的是新的(er)包也具有更標準的排序。感謝您指出這個鏈接,但我一定會建議只使用多項式包。 – askewchan