演習として tanh(x) の根を計算しようとしています。
アルゴリズムが最初の推測を求めるニュートン・ラフソン法を使用しています。
アルゴリズムは、約 1 より大きい初期推測では収束しないと想定されています。しかし、それに到達する前に数学範囲エラーが発生します。
これは私が使用しているコードです
from math import *
def f(x):#define the function
return tanh(x)
def fdiv(x):#define its derivative
return 4*(cosh(x))**2/(cosh(2*x)+1)**2
def Raphson(rx0):
return (rx0-f(rx0)/fdiv(rx0))#according to the Newton Raphson Method
def Q1_6_Raphson(rx0,Iter=1):
if Iter > 30:#maximum iterations allowed is 30
print("Newton Raphson Algorithim did not converge after 30 Trials, try other initial guesses")
return
elif fdiv(rx0)==0:
print("The initial guess you chose leads to diving by zero in the Newton-Raphson method. Choose another guess")
return
print(Iter, 'Newton-Raphson ' +str(rx0) +' error ' +str(rx0-(0)))
if rx0==0:
return
else:
return Q1_6_Raphson(Raphson(rx0),Iter=Iter+1) # call the function recursively
Q1_6Raphson(5)たとえば、実行しようとすると、次のようになります。
Traceback (most recent call last):
File "<pyshell#101>", line 1, in <module>
Q1_6_Raphson(5)
File "C:\Users\AsafHaddad\Documents\סמסטר 8\חישובית\Targil_3\Question1.6.py", line 40, in Q1_6_Raphson
return Q1_6_Raphson(Raphson(rx0),Iter=Iter+1) # call the function recursively
File "C:\Users\AsafHaddad\Documents\סמסטר 8\חישובית\Targil_3\Question1.6.py", line 33, in Q1_6_Raphson
elif fdiv(rx0)==0:
File "C:\Users\AsafHaddad\Documents\סמסטר 8\חישובית\Targil_3\Question1.6.py", line 21, in fdiv
return 4*(cosh(x))**2/(cosh(2*x)+1)**2
OverflowError: math range error
私が読んだことから、数値が大きすぎると数学範囲エラーが発生します。しかし、私が理解していないのは、私のコードで呼び出されたすべての関数が入力として 5 で問題ないということです:
>>> f(5)
0.9999092042625951
>>> fdiv(5)
0.00018158323094380672
>>> Raphson(5)
-5501.616437351696
だから問題は何ですか?数学範囲エラーの原因は何ですか?