# -*- coding: UTF-8 -*-
from math import *
############################################
# Newton法による非線形方程式(f(x)=0)の解
# fn : f(x)を計算する関数名
# dfn : f(x)の微分を計算する関数名
# x0 : 初期値
# eps1 : 終了条件1(|x(k+1)-x(k)|<eps1)
# eps2 : 終了条件2(|f(x(k))|<eps2)
# max : 最大試行回数
# ind : 実際の試行回数
# (負の時は解を得ることができなかった)
# return : 解
# coded by Y.Suganuma
############################################
def newton(fn, dfn, x0, eps1, eps2, max, ind) :
x1 = x0
x = x1
ind[0] = 0
sw = 0
while sw == 0 and ind[0] >= 0 :
sw = 1
ind[0] += 1
g = fn(x1)
if abs(g) > eps2 :
if ind[0] <= max :
dg = dfn(x1)
if abs(dg) > eps2 :
x = x1 - g / dg
if abs(x-x1) > eps1 and abs(x-x1) > eps1*abs(x) :
x1 = x
sw = 0
else :
ind[0] = -1
else :
ind[0] = -1
return x
----------------------------------
# -*- coding: UTF-8 -*-
import numpy as np
from math import *
from function import newton
############################################
# ニュートン法
# (exp(x)-3.0*x=0の根)
# coded by Y.Suganuma
############################################
# 関数値(f(x))の計算
def snx(x) :
return exp(x) - 3.0 * x
# 関数の微分の計算
def dsnx(x) :
return exp(x) - 3.0
# データの設定
ind = [0]
eps1 = 1.0e-7
eps2 = 1.0e-10
max = 20
x0 = 0.0
# 実行と結果
x = newton(snx, dsnx, x0, eps1, eps2, max, ind)
print("ind=" + str(ind[0]) + " x=" + str(x) + " f=" + str(snx(x)) + " df=" + str(dsnx(x)))