利用割线法求解一元函数极小值(Python实现)


1 问题

对于下述一元函数:
$$
\phi(\alpha)=4(1024\alpha-4)4+(2\alpha-1)2 \tag{1}
$$
求取$\phi(\alpha)$在$[0,+\infty]$上的极小点$\alpha_0$。


2 分析

利用割线法的算法进行求解,在给定初值$\alpha{-1}$和$\alpha{0}$的情况下,迭代进行求解,求解算法如下:
$$
\alpha{k+1}=\frac{\phi'(x{k})x{(k-1)}-\phi'(x{k-1})x{(k)}}{\phi'(x{k})-\phi'(x^{(k-1)})} \tag{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)

得到结果:$\alpha_0=3.67\times10^{-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 
    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)

你可能感兴趣的:(利用割线法求解一元函数极小值(Python实现))