python 拟牛顿法 求非线性方程_不动点法和牛顿法求解非线性方程的数值解(Python)...

5d3798ee5936fcd2638927cff6e59469.png

首发公众号:120701101.


一、不动点法

1、代码

# -*- coding: utf-8 -*-
"""
Created on Tue Jun 30 17:01:54 2020

@author: 120701101
@Email: 18********30@163.com

"""

# 导入相关计算库
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# 设置LaTex字体样式
from matplotlib import rcParams
config = {
    "font.family":'serif',
    "font.size": 25,
    "mathtext.fontset":'stix',
    "font.serif": ['SimSun'],
}
rcParams.update(config)


# --------------------------------fixedPoint

def fixedPoint(g, x1, stepmax, tol):
    ## g是由y=y(x)转化来的
    
    x = np.zeros(stepmax)
    x[1] = x1
    
    for n in range(1, stepmax+1):
        
        x[n+1] = g(x[n])
        
        if abs(x[n+1] - x[n]) < tol: return x[n+1]
        
        
# 求解过程                
g = lambda x: 2 ** (-x)
x_real = fixedPoint(g, 0, stepmax = 25, tol = 1.0e-6)
print("x_real = ", "{:7.6f}".format(x_real))      


# 绘制结果
plt.figure(figsize=(10,5), dpi=300)
x = np.linspace(0, 1.6, 500)
plt.plot(x,g(x), '-k', linewidth=2, label=r"$g = 2^{-x}$")
plt.plot([x[-1], x[0]], [x[-1], x[0]], linestyle="-.", color="grey")
plt.plot(x_real, g(x_real), 'o-r', markersize=15, label=r"$(0, g(0))$")

plt.xlabel(r"$x$")
plt.ylabel(r"$y(x)$")
plt.title("不动点法求解非线性函数的根", fontsize=20)
plt.xlim((0, 1.6))
plt.xticks(np.arange(0, 1.7, 0.2))
plt.legend()
plt.grid(True, linestyle='-.')
plt.annotate("这是" + r"$x=2^{-x}$" + "的解", xy=(x_real, g(x_real)),
             xytext=(x_real-0.1, g(x_real)+0.35),
             arrowprops=dict(arrowstyle="->",connectionstyle="arc3,rad=.2"))

plt.show()

2、计算结果

运行代码即可得到,

x_real =  0.641186

3、图像结果

685d05ab1ff1670e8561ec0d0896732b.png
不动点法

二、牛顿法

1、代码

# -*- coding: utf-8 -*-
"""
Created on Tue Jun 30 18:12:53 2020

@author: 120701101
@Email: 18********30@163.com

"""

import numpy as np
from numpy import sign
import matplotlib
import matplotlib.pyplot as plt

from matplotlib import rcParams

config = {
    "font.family":'serif',
    "font.size": 25,
    "mathtext.fontset":'stix',
    "font.serif": ['SimSun'],
}
rcParams.update(config)

# ----------------------------newton

def newton(fun, df, x1, stepmax, tol):
    ## df是原方程的导数方程
    x = np.zeros(stepmax+1)
    x[1] = x1
    
    for k in range(1, stepmax+1):
        
        if sign(df(x[k])) == 0: return print("请重新输入正确的初始值")
        
        x[k+1] = x[k] - fun(x[k]) / df(x[k])
        
        if abs(x[k+1] - x[k]) < tol: return x[k+1]
        
        
# 求解过程                
fun = lambda x: x * np.cos(x) + 1
df = lambda x: np.cos(x) - x * np.sin(x)
x_real = newton(fun, df, 1, stepmax = 25, tol = 1.0e-6)
print("x_real = ", "{:7.6f}".format(x_real))
            

# 绘制结果
plt.figure(figsize=(10,5), dpi=300)
x = np.linspace(-3, 5, 500)
plt.plot(x,fun(x), '-k', linewidth=2, label=r"$y = x cdot cosx + 1$")
plt.plot(x_real, fun(x_real), 'o-r', markersize=15, label=r"$(0, y(0))$")

plt.xlabel(r"$x$")
plt.ylabel(r"$y(x)$")
plt.title("牛顿法求解非线性函数的根", fontsize=20)
plt.xlim((-3, 5))
plt.xticks(np.arange(-3, 6, 1))
plt.legend()
plt.grid(True, linestyle='-.')

plt.show()

2、计算结果

运行代码即可得到,

x_real =  2.073933

3、图像结果

3ffc1d6a0a6aeff95e8f1a7f0a01fa28.png
牛顿法

三、简评

python写的牛顿法不如matlab的方便,python写的需要自己先求出原非线性方程的导数方程,没有像matlab的matlabFunction符号函数转化为句柄函数的函数功能。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值