[英]How to find a root for a mathematical function using Intermediate value theorem?
根據給定函數F(x)的中間值定理,我應該寫一個函數,該函數獲得一個數學函數,兩個數字a和b以及一個誤差范圍,並給出輸出x對於該函數,其值直到epsilon都接近於0。 例子:
>>> find_root(lambda x : x - 1 , -10, 10)
1.0009765625
>>> find_root(lambda x : x**2 , -10, 10)
>>> #returned None
這是我到目前為止編寫的代碼,我認為我的方法是正確的,但是我無法弄清楚要進行循環的內容,因此我無法獲得正確的答案。 那我該怎么解決呢?
def find_root(f, a, b, EPS=0.001):
if (f(a)*f(b))<0:
for i in range(a,b):
if f(i)<EPS:
return (i)
else:
return (None)
使用二分法:
def find_root(f, a, b, EPS=0.0001):
if f(a)==0 : return a
if f(b)==0 : return b
if f(a)*f(b)>0 : return None
c=(a+b)/2
while(abs(f(c))>EPS) :
if f(a)*f(c)<0 : b=c
else : a=c
c=(a+b)/2
return c
最簡單的解決方案是這樣的:
def find_root(f, a, b, EPS=0.001):
#assuming a < b
x = a
while x <= b:
if abs(f(x)) < EPS:
return x
else:
x += EPS
結果:
>>>find_root(lambda x: x-1, -10, 10)
0.9999999999998982
>>>find_root(lambda x: x-1, -10, -2)
None
如您所知,如果初始值均為正數或均為負數,則過程找不到根。
這是關於如何使用二進制搜索來實現它的建議,以加快該過程:
def find_root(f, a, b, EPS=0.001):
fa = f(a)
fb = f(b)
if fa*fb > 0: # both positive or both negative
return None
while abs(fa) > EPS and abs(fb) > EPS:
c = (a+b)/2.0
fc = f(c)
if fa*fc >= 0:
a = c
fa = fc
else:
b = c
fb = fc
if abs(fa) <= EPS:
return a
else:
return b
find_root(lambda x : x-1, -10, 10)
的返回值為1.0009765625。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.