Python数值方法及数据可视化
作者:Chandler_river 发布时间:2021-07-26 17:32:51
标签:Python,数值,可视化
随机数和蒙特卡洛模拟
求解单一变量非线性方程
求解线性系统方程
函数的数学积分
常微分方程的数值解
等势线绘图和曲线:
等势线
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x_vals = np.linspace(-5,5,20)
y_vals = np.linspace(0,10,20)
X,Y = np.meshgrid(x_vals,y_vals)
Z = X**2 * Y**0.5
line_count = 15
ax = Axes3D(plt.figure())
ax.plot_surface(X,Y,Z,rstride=1,cstride=1)
plt.show()
非线性方程的数学解:
一般实函数 Scipy.optimize
fsolve函数求零点(限定只给实数解)
import scipy.optimize as so
from scipy.optimize import fsolve
f = lambda x:x**2-1
fsolve(f,0.5)
fsolve(f,-0.5)
fsolve(f,[-0.5,0.5])
>>>fsolve(f,-0.5,full_output=True)
>>>(array([-1.]), {'nfev': 9, 'fjac': array([[-1.]]), 'r': array([1.99999875]), 'qtf': array([3.82396337e-10]), 'fvec': array([4.4408921e-16])}, 1, 'The solution converged.')
>>>help(fsolve)
>>>Help on function fsolve in module scipy.optimize._minpack_py:
fsolve(func, x0, args=(), fprime=None, full_output=0, col_deriv=0, xtol=1.49012e-08, maxfev=0, band=None, epsfcn=None, factor=100, diag=None)
Find the roots of a function.
Return the roots of the (non-linear) equations defined by
``func(x) = 0`` given a starting estimate.
Parameters
----------
func : callable ``f(x, *args)``
A function that takes at least one (possibly vector) argument,
and returns a value of the same length.
x0 : ndarray
The starting estimate for the roots of ``func(x) = 0``.
args : tuple, optional
Any extra arguments to `func`.
fprime : callable ``f(x, *args)``, optional
A function to compute the Jacobian of `func` with derivatives
across the rows. By default, the Jacobian will be estimated.
full_output : bool, optional
If True, return optional outputs.
col_deriv : bool, optional
Specify whether the Jacobian function computes derivatives down
the columns (faster, because there is no transpose operation).
xtol : float, optional
The calculation will terminate if the relative error between two
consecutive iterates is at most `xtol`.
maxfev : int, optional
The maximum number of calls to the function. If zero, then
``100*(N+1)`` is the maximum where N is the number of elements
in `x0`.
band : tuple, optional
If set to a two-sequence containing the number of sub- and
super-diagonals within the band of the Jacobi matrix, the
Jacobi matrix is considered banded (only for ``fprime=None``).
epsfcn : float, optional
A suitable step length for the forward-difference
approximation of the Jacobian (for ``fprime=None``). If
`epsfcn` is less than the machine precision, it is assumed
that the relative errors in the functions are of the order of
the machine precision.
factor : float, optional
A parameter determining the initial step bound
(``factor * || diag * x||``). Should be in the interval
``(0.1, 100)``.
diag : sequence, optional
N positive entries that serve as a scale factors for the
variables.
Returns
-------
x : ndarray
The solution (or the result of the last iteration for
an unsuccessful call).
infodict : dict
A dictionary of optional outputs with the keys:
``nfev``
number of function calls
``njev``
number of Jacobian calls
``fvec``
function evaluated at the output
``fjac``
the orthogonal matrix, q, produced by the QR
factorization of the final approximate Jacobian
matrix, stored column wise
``r``
upper triangular matrix produced by QR factorization
of the same matrix
``qtf``
the vector ``(transpose(q) * fvec)``
ier : int
An integer flag. Set to 1 if a solution was found, otherwise refer
to `mesg` for more information.
mesg : str
If no solution is found, `mesg` details the cause of failure.
See Also
--------
root : Interface to root finding algorithms for multivariate
functions. See the ``method=='hybr'`` in particular.
Notes
-----
``fsolve`` is a wrapper around MINPACK's hybrd and hybrj algorithms.
Examples
--------
Find a solution to the system of equations:
``x0*cos(x1) = 4, x1*x0 - x1 = 5``.
>>> from scipy.optimize import fsolve
>>> def func(x):
... return [x[0] * np.cos(x[1]) - 4,
... x[1] * x[0] - x[1] - 5]
>>> root = fsolve(func, [1, 1])
>>> root
array([6.50409711, 0.90841421])
>>> np.isclose(func(root), [0.0, 0.0]) # func(root) should be almost 0.0.
array([ True, True])
关键字参数: full_output=True
多项式的复数根 :np.roots([最高位系数,次高位系数,... ... x项系数,常数项])
>>>f = lambda x:x**4 + x -1
>>>np.roots([1,0,0,1,-1])
>>>array([-1.22074408+0.j , 0.24812606+1.03398206j,
0.24812606-1.03398206j, 0.72449196+0.j ])
求解线性等式 scipy.linalg
利用dir()获取常用函数
import numpy as np
import scipy.linalg as sla
from scipy.linalg import inv
a = np.array([-1,5])
c = np.array([[1,3],[3,4]])
x = np.dot(inv(c),a)
>>>x
>>>array([ 3.8, -1.6])
数值积分 scipy.integrate
利用dir()获取你需要的信息
对自定义函数做积分
import scipy.integrate as si
from scipy.integrate import quad
import numpy as np
import matplotlib.pyplot as plt
f = lambda x:x**1.05*0.001
interval = 100
xmax = np.linspace(1,5,interval)
integral,error = np.zeros(xmax.size),np.zeros(xmax.size)
for i in range(interval):
integral[i],error[i] = quad(f,0,xmax[i])
plt.plot(xmax,integral,label="integral")
plt.plot(xmax,error,label="error")
plt.show()
对震荡函数做积分
quad 函数允许 调整他使用的网格
>>>(-0.4677718053224297, 2.5318630220102742e-05)
>>>quad(np.cos,-1,1,limit=100)
>>>(1.6829419696157932, 1.8684409237754643e-14)
>>>quad(np.cos,-1,1,limit=1000)
>>>(1.6829419696157932, 1.8684409237754643e-14)
>>>quad(np.cos,-1,1,limit=10)
>>>(1.6829419696157932, 1.8684409237754643e-14)
微分方程的数值解 参见 Python数值求解微分方程方法(欧拉法,隐式欧拉)
向量场与流线图:
vector(x,y) = (y,-x)
import numpy as np
import matplotlib.pyplot as plt
coords = np.linspace(-1,1,30)
X,Y = np.meshgrid(coords,coords)
Vx,Vy = Y,-X
plt.quiver(X,Y,Vx,Vy)
plt.show()
------------------
import numpy as np
import matplotlib.pyplot as plt
coords = np.linspace(-2,2,10)
X,Y = np.meshgrid(coords,coords)
Z = np.exp(np.exp(X+Y))
ds = 4/6
dX,dY = np.gradient(Z,ds)
plt.contourf(X,Y,Z,25)
plt.quiver(X,Y,dX.transpose(),dY.transpose(),scale=25)
plt.show()
来源:https://blog.csdn.net/Chandler_river/article/details/126270892
0
投稿
猜你喜欢
- 准备篇1.配置防火墙,开启80端口、3306端口1 vim /etc/sysconfig/iptables2 -A INPUT -m sta
- 如何在网站上提供音乐下载?为用户提供歌曲下载,一般有两种方式,一是直接通过Http,浏览器下载,二是通过ftp协议下载。我们来用Http和浏
- 数据处理在现代企业运营中变得越来越重要,越来越关键,甚至会成为企业发展的一项瓶颈. 数据保护的重要性也不言而喻. 如果一个企业没有很好的数据
- 本程序是利用3.x的Firefox浏览器可以读取本地文件的特性,实现通过xmlHttPRequest上传大文件功能,并在可以上传过程中动态显
- 本文实例讲述了Python进程的通信Queue、Pipe。分享给大家供大家参考,具体如下:内容相关:概念:进程的通信Queue:创建与使用P
- 这是为了实现一个效果,而提前作的测试代码!看起来很简单的一个东西,到这会,大约四个小时过去了。不知道是IE6的BUG;还是我自已的BUG!有
- 问题引入什么时候选择 T 作为参数类型,什么时候选择 *T 作为参数类型?[ ] T 是传递的指针还是值?选择 [ ] T 还是 [ ] *
- asp在线备份sql server数据库: 1、备份sqlserver 代码如下:<% SQL="backup&n
- 某天和一个产品经理聊起:以用户为中心是一个理想概念。经历了太多的项目,看到了太多的限制条件。而我向来不是一个有着设计洁癖的完美主义者。做为所
- 以下所有代码全是在<head>...</head>之间,具体内容有:1,<title>…</tit
- 官方的说法: classmethod(function)中文说明:classmethod是用来指定一个类的方法为类方法,没有此参数指定的类的
- 首先介绍下简朝阳.现就职于阿里巴巴(中国)网络技术有限公司DBA Team运维部, 简朝阳是本次MYSQL技术征文大赛第三名得主(获奖文章:
- 本文实例讲述了Python开发微信公众平台的方法。分享给大家供大家参考,具体如下:这两天将之前基于微信公众平台的代码重构了下,基础功能以库的
- 国外有很多优秀的文章可以用来学习,我决定花些时间翻译。我并不知道这篇文章有没有人翻译过,原文名 10 Awful IE Bugs and F
- 一、引用计数基础知识每个php变量存在一个叫 zval 的变量容器中。一个 zval 变量容器,除了包含变量的类型和值,还包括两个字节的额外
- 前言上篇文章讲的进阶一些的PHP特性不知道大家吸收的怎么样了,今天作为本PHP特性函数的最后一篇,我也会重点介绍一些有趣的PHP特性以及利用
- 一. 建库,建表,加约束. 1.1建库 代码如下:use master go if exists (select * from sysdat
- 我们在使用很多新闻系统的时候,都会发现一个问题,尤其是使用 HtmlEdit 从WORD文档中直接拷贝文章(尤其里面有复杂表格和文字)的时候
- 安装官网下载http://ffmpeg.org/选择需要的版本在这个网址下载ffmpeg,https://github.com/BtbN/F
- 我们经常使用傅里叶变换来计算数字信号的频谱,进而分析数字信号,离散时间傅里叶变换的公式为:可是自己动手实现一遍才是最好的学习。在数字分析里面