• 随机数和蒙特卡洛模拟
  • 求解单一变量非线性方程
  • 求解线性系统方程
  • 函数的数学积分
  • 常微分方程的数值解

等势线绘图和曲线:

等势线 

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()

到此这篇关于Python数值方法及数据可视化的文章就介绍到这了,更多相关Python数值 视化内容请搜索Devmax以前的文章或继续浏览下面的相关文章希望大家以后多多支持Devmax!

Python数值方法及数据可视化的更多相关文章

  1. XCode 3.2 Ruby和Python模板

    在xcode3.2下,我的ObjectiveCPython/Ruby项目仍然可以打开更新和编译,但是你无法创建新项目.鉴于xcode3.2中缺少ruby和python的所有痕迹(即创建项目并添加新的ruby/python文件),是否有一种简单的方法可以再次安装模板?我发现了一些关于将它们复制到某个文件夹的信息,但我似乎无法让它工作,我怀疑文件夹的位置已经改变为3.2.解决方法3.2中的应用程序模板

  2. 如何在Xcode 8中启用Visual Memory Debugger?

    我将项目从以前版本的Xcode迁移到Xcode8.我想要的是使用新的可视化内存调试器.它可用于新项目,但在我导入的项目中完全缺少.为什么是这样?

  3. Swift基本使用-函数和闭包(三)

    声明函数和其他脚本语言有相似的地方,比较明显的地方是声明函数的关键字swift也出现了Python中的组元,可以通过一个组元返回多个值。传递可变参数,函数以数组的形式获取参数swift中函数可以嵌套,被嵌套的函数可以访问外部函数的变量。可以通过函数的潜逃来重构过长或者太复杂的函数。

  4. 10 个Python中Pip的使用技巧分享

    众所周知,pip 可以安装、更新、卸载 Python 的第三方库,非常方便。本文小编为大家总结了Python中Pip的使用技巧,需要的可以参考一下

  5. Swift - 继承UIView实现自定义可视化组件附记分牌样例

    在iOS开发中,如果创建一个自定义的组件通常可以通过继承UIView来实现。下面以一个记分牌组件为例,演示了组件的创建和使用,以及枚举、协议等相关知识的学习。效果图如下:组件代码:scoreView.swift123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051importUIKitenumscoreType{caseCommon//普通分数面板Best//最高分面板}pr

  6. Swift、Go、Julia与R能否挑战 Python 的王者地位

    本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请发送邮件至dio@foxmail.com举报,一经查实,本站将立刻删除。

  7. 红薯因 Swift 重写开源中国失败,貌似欲改用 Python

    本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请发送邮件至dio@foxmail.com举报,一经查实,本站将立刻删除。

  8. 你没看错:Swift可以直接调用Python函数库

    上周Perfect又推出了新一轮服务器端Swift增强函数库:Perfect-Python。对,你没看错,在服务器端Swift其实可以轻松从其他语种的函数库中直接拿来调用,不需要修改任何内容。以如下python脚本为例:Perfect-Python可以用下列方法封装并调用以上函数,您所需要注意的仅仅是其函数名称以及参数。

  9. Swift中的列表解析

    在Swift中完成这个的最简单的方法是什么?我在寻找类似的东西:从Swift2.x开始,有一些与你的Python样式列表解析相当的东西。(在这个意义上,它更像是Python的xrange。如果你想保持集合懒惰一路通过,只是这样说:与Python中的列表解析语法不同,Swift中的这些操作遵循与其他操作相同的语法。

  10. 使用自动布局可视化格式与Swift?

    我一直在试图使用AutolayoutVisualFormatLanguageinSwift,使用NSLayoutConstraint.constraintsWithVisualFormat。这里有一些例子,没有什么有用的代码,但就我可以告诉应该让类型检查器快乐:但是,这会触发编译器错误:“Cannotconverttheexpression’stype‘[AnyObject]!’totype‘St

随机推荐

  1. 10 个Python中Pip的使用技巧分享

    众所周知,pip 可以安装、更新、卸载 Python 的第三方库,非常方便。本文小编为大家总结了Python中Pip的使用技巧,需要的可以参考一下

  2. python数学建模之三大模型与十大常用算法详情

    这篇文章主要介绍了python数学建模之三大模型与十大常用算法详情,文章围绕主题展开详细的内容介绍,具有一定的参考价值,感想取得小伙伴可以参考一下

  3. Python爬取奶茶店数据分析哪家最好喝以及性价比

    这篇文章主要介绍了用Python告诉你奶茶哪家最好喝性价比最高,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧

  4. 使用pyinstaller打包.exe文件的详细教程

    PyInstaller是一个跨平台的Python应用打包工具,能够把 Python 脚本及其所在的 Python 解释器打包成可执行文件,下面这篇文章主要给大家介绍了关于使用pyinstaller打包.exe文件的相关资料,需要的朋友可以参考下

  5. 基于Python实现射击小游戏的制作

    这篇文章主要介绍了如何利用Python制作一个自己专属的第一人称射击小游戏,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起动手试一试

  6. Python list append方法之给列表追加元素

    这篇文章主要介绍了Python list append方法如何给列表追加元素,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  7. Pytest+Request+Allure+Jenkins实现接口自动化

    这篇文章介绍了Pytest+Request+Allure+Jenkins实现接口自动化的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  8. 利用python实现简单的情感分析实例教程

    商品评论挖掘、电影推荐、股市预测……情感分析大有用武之地,下面这篇文章主要给大家介绍了关于利用python实现简单的情感分析的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下

  9. 利用Python上传日志并监控告警的方法详解

    这篇文章将详细为大家介绍如何通过阿里云日志服务搭建一套通过Python上传日志、配置日志告警的监控服务,感兴趣的小伙伴可以了解一下

  10. Pycharm中运行程序在Python console中执行,不是直接Run问题

    这篇文章主要介绍了Pycharm中运行程序在Python console中执行,不是直接Run问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

返回
顶部