SciPy库为Python提供了科学计算的基本算法
基本操作
求解非线性方程(组)
scipy.optimize模块的fsolve和root可求非线性方程(组)的解
fsolve或root求解非线性方程组时,先把非线性方程组写成 F(x)=0 这样的形式,其中,x为向量,F(x)为向量函数
scipy.optimize.fsolve
(func, x0, args(), fprime=None, full_output=0, col_deriv=0, xtol=1.49012e08, maxfev=0,
band=None, epsfcn=None, factor=100, diag=None)
scipy.optimize.root
(fun, x0, args(), method='hybr', jac=None, tol=None, callback=None, options=None)
其中,fun为函数,x0为猜测值
例1
from scipy.optimize import fsolve, root
fx = lambda x: x ** 980 - 5.01 * x ** 979 + 7.398 * x ** 978 \
- 3.388 * x ** 977 - x ** 3 + 5.01 * x ** 2 - 7.398 * x + 3.388
x1 = fsolve(fx, 1.5, maxfev=4000) # 函数调用4000次
x2 = root(fx, 1.5)
print(x1, '\n')
print(x2)
'''
输出:
[1.21]
message: The solution converged.
success: True
status: 1
fun: [-1.235e+69]
x: [ 1.210e+00]
nfev: 319
fjac: [[-1.000e+00]]
r: [ 2.542e+80]
qtf: [ 2.002e+72]
'''
例2
rom scipy.optimize import fsolve, root
fx = lambda x: [x[0] ** 2 + x[1] ** 2 - 1, x[0] - x[1]]
s1 = fsolve(fx, [1, 1])
s2 = root(fx, [1, 1])
print(s1, '\n')
print('s2=', s2)
'''
[0.70710678 0.70710678]
s2= message: The solution converged.
success: True
status: 1
fun: [ 4.441e-16 0.000e+00]
x: [ 7.071e-01 7.071e-01]
nfev: 9
fjac: [[-8.165e-01 -5.773e-01]
[ 5.773e-01 -8.165e-01]]
r: [-1.732e+00 -5.774e-01 1.633e+00]
qtf: [-3.646e-10 2.578e-10]
'''
积分
scipy.integrate模块提供了多种积分模式,主要是对给定函数或离散点的数值积分
例3
from scipy.integrate import quad
def fun46(x, a, b):
return a * x ** 2 + b * x
I1 = quad(fun46, 0, 1, args=(2, 1)) # 0, 1是积分上下限;args=(2, 1)是参数a,b的值
I2 = quad(fun46, 0, 1, args=(2, 10))
print('I1=', I1)
print('I2=', I2)
'''
I1= (1.1666666666666665, 1.2952601953960159e-14)
I2= (5.666666666666667, 6.291263806209221e-14)
'''
最小二乘解
调用形式:
from scipy.optimize import least_squares
least_square(fun,x0)
其中fun是定义向量函数 的匿名函数的返回值,x0为x的初始值
最大模特征值及对应的特征向量
例4
from scipy.sparse.linalg import eigs
import numpy as np
a = np.array([[1, 2, 3], [2, 1, 3], [3, 3, 6]], dtype=float)
b, c = np.linalg.eig(a)
d, e = eigs(a, 1)
print('特征值为', b)
print('特征向量为', c)
print('最大模特征值为:', d)
print('对应的特征向量为:\n', e)
'''
特征值为 [ 9.0000000e+00 -1.0000000e+00 1.8525281e-16]
特征向量为 [[-4.08248290e-01 -7.07106781e-01 -5.77350269e-01]
[-4.08248290e-01 7.07106781e-01 -5.77350269e-01]
[-8.16496581e-01 -2.70689541e-16 5.77350269e-01]]
最大模特征值为: [9.+0.j]
对应的特征向量为:
[[0.40824829+0.j]
[0.40824829+0.j]
[0.81649658+0.j]]
'''
标签:None,01,Python,fsolve,00,scipy,print,SciPy
From: https://blog.csdn.net/weixin_73042028/article/details/137259703