'''Author: P Shreyas ShettyImplementation of Newton-Raphson method for solving equations of kindf(x) = 0. It is an iterative method where solution is found by the expressionx[n+1] = x[n] + f(x[n])/f'(x[n])If no solution exists, then either the solution will not be found when iterationlimit is reached or the gradient f'(x[n]) approaches zero. In both cases, exceptionis raised. If iteration limit is reached, try increasing maxiter.'''import math as mdef calc_derivative(f, a, h=0.001):'''Calculates derivative at point a for function f using finite differencemethod'''return (f(a+h)-f(a-h))/(2*h)def newton_raphson(f, x0=0, maxiter=100, step=0.0001, maxerror=1e-6,logsteps=False):a = x0 #set the initial guesssteps = [a]error = abs(f(a))f1 = lambda x:calc_derivative(f, x, h=step) #Derivative of f(x)for _ in range(maxiter):if f1(a) == 0:raise ValueError("No converging solution found")a = a - f(a)/f1(a) #Calculate the next estimateif logsteps:steps.append(a)error = abs(f(a))if error < maxerror:breakelse:raise ValueError("Itheration limit reached, no converging solution found")if logsteps:#If logstep is true, then log intermediate stepsreturn a, error, stepsreturn a, errorif __name__ == '__main__':import matplotlib.pyplot as pltf = lambda x:m.tanh(x)**2-m.exp(3*x)solution, error, steps = newton_raphson(f, x0=10, maxiter=1000, step=1e-6, logsteps=True)plt.plot([abs(f(x)) for x in steps])plt.xlabel("step")plt.ylabel("error")plt.show()print("solution = {%f}, error = {%f}" % (solution, error))
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。