为什么每次连续迭代的代码输出都会变慢?
我想编写一个工作代码,在同一函数上实现梯度下降和牛顿方法,我想比较这两种方法的速度和迭代次数,以得出近似解。
此代码段仅适用于Gradient descent,并且每次迭代的输出似乎都变慢。所以我得到的前10个输出相对快,之后每个输出至少需要5-6秒甚至更多。
#A python program to approximate a root of a polynomial
#using the newton-raphson method
import math
#f(x) - the function of the polynomial
h = 0.000001
def f(x):
function = (x*x*x) - (2*x) - 1
return function
def derivative(h,x): #function to find the derivative of the polynomial
derivative = (f(x + h) - f(x)) / h
return derivative
def GD(h,x):
return (x - h*derivative(h,x))
# p - the initial point i.e. a value closer to the root
# n - number of iterations
def iterate(p, n): #
x = 0
for i in range(n):
if i == 0: #calculate first approximation
x = GD(h,p)
else:
x = GD(h,iterate(x, n)) #iterate the first and subsequent approximations
n=n-1
return x
for i in range(100):
print (iterate(1, i)) #print the root of the polynomial x^3 - 2x - 1 using 3 iterations and taking initial point as 1
我不知道是由于代码还是梯度下降而发生的。