[英]Fsolve precision issue (python)
我遇到了 fsolve 的精度問題。
import numpy as np
from scipy.optimize import fsolve
ens=np.arange(0,50,1)
def f(x):
return x*(np.sin(x)/np.cos(x))-1000
s=[]
roots=fsolve(f,ens)
roots=np.around(roots, decimals=3 , out=None)
a = roots[roots >= 0]
g = np.unique(a)
g=g[:5]
s.append(g)
print(s)
result :
[array([10.842, 11.006, 15.165, 21.116, 22.382])]
結果應該是:[ 1.569,4.708,7.846 ,10.985,14.123]
我的代碼錯過了前三個解決方案,其他的都不准確。 您知道如何提高結果的精度嗎?
您可以使用scipy.optimize.newton()
與 function f
的一階和二階導數來獲得更准確的結果。 您可以手動完成,或使用導數計算器.net 或wolframalpha
。 將一階導數fprime
和二階導數fprime2
給newton()
。 如果您這樣做,將使用Halley 方法而不是更准確的簡單Newton-Raphson方法(請參閱newton()
文檔中fprime2
下面的描述)。
def f(x):
return x*(np.sin(x)/np.cos(x))-1000
def fprime(x):
# first derivative of f
# do this by hand or use derivative-calculator.net or wolframalpha
return np.tan(x)+ x*(1/np.cos(x))**2
def fprime2(x):
# second derivative of f
# do this by hand or use derivative-calculator.net or wolframalpha
return 2*1/(np.cos(x)**2)*(x*np.tan(x)+1)
res = newton(f,x0=[1,4,7,10,14],fprime=fprime, fprime2=fprime2)
res = np.around(res, decimals=3)
res
將是:
array([ 1.569, 4.708, 7.846, 10.985, 14.123])
上面newton()
中的x0
參數是所謂的根在哪里的初始猜測列表。 由於您的 function 有無限多的根(請參閱下面的 plot),因此傳遞其中一些有助於獲得您真正關心的根。
這就是f
的樣子(嗯, f/1000
使特征可見):
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.