您的位置:首页 > 其它

利用割线法求解一元函数极小值

2017-04-27 23:44 471 查看

优化理论__利用割线法求解一元函数极小值(Python实现)

1 问题

对于下述一元函数:

ϕ(α)=4(1024α−4)4+(2α−1)2(1)

求取ϕ(α)在[0,+∞]上的极小点α0。

2 分析

利用割线法的算法进行求解,在给定初值α−1和α0的情况下,迭代进行求解,求解算法如下:

αk+1=ϕ′(xk)x(k−1)−ϕ′(xk−1)x(k)ϕ′(xk)−ϕ′(x(k−1))(2)

3 编程实现

利用Python进行实现:

import sys

def derivative(x, dx=1e-6):
# Computes the numerical derivative of a function.
return (g(x+dx) - g(x)) / dx

def g(x):
return 4*(1024*x-4)**4 + (2*x-1)**2

def secant_method(aList):
a = aList[-1]
b = aList[-2]
numerator = float(derivative(a)*b - derivative(b)*a)
denominator = float(derivative(a) - derivative(b))
step_length = numerator / denominator
if g(step_length) < g(aList[-1]):
aList.append(step_length)
secant_method(aList)
else:
return aList

aList = [1, 0.5]
finalList = secant_method(aList)
answer = finalList[-1]
print(answer)


得到结果:α0=3.67×10−3

4 遇到的问题

问题

最开始采用以下代码:

aList = [1, 0.5]
finalList = secant_method(aList)
answer = finalList[-1]
print(answer)


报错如下:

Traceback (most recent call last):
File "G:/PyCharm/PycharmProjects/Optimization/An introduction to optimization/diff.py", line 25, in <module>
answer = finalList[-1]
TypeError: 'NoneType' object is not subscriptable

Process finished with exit code 1


问题原因

报错原因在于列表被函数调用是一个in-place过程,将其赋给另一个对象时,传递的是一个None类型的数据

解决办法

修改为以下代码即可:

aList = [1, 0.5]
secant_method(aList)
answer = aList[-1]
print(answer)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: