牛顿下山法(Python实现)

目录

1、原理

2、案例 

3、Python实现 

4、结果

5、展望


1、原理

2、案例 

3、Python实现 

import numpy as np

# Store the iteration value of each step
result = []
# Store downhill factors for each step
all_r = []


# Judge whether it is singular. True is singular and false is nonsingular
def strange(xk):
    return True if (0.5*xk**(-1/2)-3*xk**2) == 0 else False


# Primitive function
def fx(xk):
    return xk**(1/2)-xk**3+2


# Newton iterative formula
# xk is the iterative value and r is the downhill factor
def nd(xk, r):
    return xk - fx(xk) / (0.5*xk**(-1/2)-3*xk**2) * r


# Newton downhill formula
# return True Downhill success  False Downhill failure
def nd_xs(xk, m):
    r = 1
    count = 1
    while True:
        if count > m:
            return False

        xk1 = nd(xk, r)
        if abs(fx(xk1)) < abs(fx(xk)):
            result.append(xk1)
            all_r.append(r)
            return True
        else:
            r *= 0.5

        count += 1


# Main function
def main():
    # initial value
    x = float(input("Please enter the initial value:"))
    result.append(x)
    # Error limit
    e = float(input("Please enter the error limit:"))
    # Maximum number of iterations
    n = int(input("Please enter the maximum number of iterations:"))
    # Maximum number of downhill
    m = int(input("Please enter the maximum number of times to go down the mountain:"))

    # Number of iterations
    ite = 1
    while True:
        if ite > n:
            print("Number of iterations exceeded!")
            return

        if strange(result[-1]):
            print("Singular, denominator zero!")
            return

        if not nd_xs(result[-1], m):
            print("Downhill failure!")
            return

        if abs(result[-1] - result[-2]) < e:
            print("Downhill factor of each step:" + str(all_r))
            print("Iteration value of each step (including initial value):" + str(result))
            return

        ite += 1

if __name__ =='__main__':
    main()

4、结果

Please enter the initial value:1.5
Please enter the error limit:0.00001
Please enter the maximum number of iterations:100000
Please enter the maximum number of times to go down the mountain:100000
Downhill factor of each step:[1, 1, 1]
Iteration value of each step (including initial value):[1.5, 1.4763069991556952, 1.4758905899820982, 1.4758904626019806]

5、展望

 

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

荔枝科研社

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值