python3的sympy

Python010

python3的sympy,第1张

print(“字符串”),5/2和5//2的结果是不同的5/2为2.5,5//2为2.

python2需要导入from_future_import division执行普通的除法。

1/2和1//2的结果0.5和0.

%号为取模运算。

乘方运算为2**3,-2**3和-(2**3)是等价的。

from sympy import*导入库

x,y,z=symbols('x y z'),定义变量

init_printing(use_unicode=True)设置打印方式。

python的内部常量有pi,

函数simplify,simplify(sin(x)**2 + cos(x)**2)化简结果为1,

simplify((x**3 + x**2 - x - 1)/(x**2 + 2*x + 1))化简结果为x-1。化简伽马函数。simplify(gamma(x)/gamma(x - 2))得(x-2)(x-1)。

expand((x + 1)**2)展开多项式。

expand((x + 1)*(x - 2) - (x - 1)*x)

因式分解。factor(x**2*z + 4*x*y*z + 4*y**2*z)得到z*(x + 2*y)**2

from_future_import division

x,y,z,t=symbols('x y z t')定义变量,

k, m, n = symbols('k m n', integer=True)定义三个整数变量。

f, g, h = symbols('f g h', cls=Function)定义的类型为函数。

factor_list(x**2*z + 4*x*y*z + 4*y**2*z)得到一个列表,表示因式的幂,(1, [(z, 1), (x + 2*y, 2)])

expand((cos(x) + sin(x))**2)展开多项式。

expr = x*y + x - 3 + 2*x**2 - z*x**2 + x**3,collected_expr = collect(expr, x)将x合并。将x元素按阶次整合。

collected_expr.coeff(x, 2)直接取出变量collected_expr的x的二次幂的系数。

cancel()is more efficient thanfactor().

cancel((x**2 + 2*x + 1)/(x**2 + x))

,expr = (x*y**2 - 2*x*y*z + x*z**2 + y**2 - 2*y*z + z**2)/(x**2 - 1),cancel(expr)

expr = (4*x**3 + 21*x**2 + 10*x + 12)/(x**4 + 5*x**3 + 5*x**2 + 4*x),apart(expr)

asin(1)

trigsimp(sin(x)**2 + cos(x)**2)三角函数表达式化简,

trigsimp(sin(x)**4 - 2*cos(x)**2*sin(x)**2 + cos(x)**4)

trigsimp(sin(x)*tan(x)/sec(x))

trigsimp(cosh(x)**2 + sinh(x)**2)双曲函数。

三角函数展开,expand_trig(sin(x + y)),acos(x),cos(acos(x)),expand_trig(tan(2*x))

x, y = symbols('x y', positive=True)正数,a, b = symbols('a b', real=True)实数,z, t, c = symbols('z t c')定义变量的方法。

sqrt(x) == x**Rational(1, 2)判断是否相等。

powsimp(x**a*x**b)幂函数的乘法,不同幂的乘法,必须先定义a和b。powsimp(x**a*y**a)相同幂的乘法。

powsimp(t**c*z**c),注意,powsimp()refuses to do the simplification if it is not valid.

powsimp(t**c*z**c, force=True)这样的话就可以得到化简过的式子。声明强制进行化简。

(z*t)**2,sqrt(x*y)

第一个展开expand_power_exp(x**(a + b)),expand_power_base((x*y)**a)展开,

expand_power_base((z*t)**c, force=True)强制展开。

powdenest((x**a)**b),powdenest((z**a)**b),powdenest((z**a)**b, force=True)

ln(x),x, y ,z= symbols('x y z', positive=True),n = symbols('n', real=True),

expand_log(log(x*y))展开为log(x) + log(y),但是python3没有。这是因为需要将x定义为positive。这是必须的,否则不会被展开。expand_log(log(x/y)),expand_log(log(x**n))

As withpowsimp()andpowdenest(),expand_log()has aforceoption that can be used to ignore assumptions。

expand_log(log(z**2), force=True),强制展开。

logcombine(log(x) + log(y)),logcombine(n*log(x)),logcombine(n*log(z), force=True)。

factorial(n)阶乘,binomial(n, k)等于c(n,k),gamma(z)伽马函数。

hyper([1, 2], [3], z),

tan(x).rewrite(sin)得到用正弦表示的正切。factorial(x).rewrite(gamma)用伽马函数重写阶乘。

expand_func(gamma(x + 3))得到,x*(x + 1)*(x + 2)*gamma(x),

hyperexpand(hyper([1, 1], [2], z)),

combsimp(factorial(n)/factorial(n - 3))化简,combsimp(binomial(n+1, k+1)/binomial(n, k))化简。combsimp(gamma(x)*gamma(1 - x))

自定义函数

def list_to_frac(l):

expr = Integer(0)

for i in reversed(l[1:]):

expr += i

expr = 1/expr

return l[0] + expr

list_to_frac([x, y, z])结果为x + 1/z,这个结果是错误的。

syms = symbols('a0:5'),定义syms,得到的结果为(a0, a1, a2, a3, a4)。

这样也可以a0, a1, a2, a3, a4 = syms, 可能是我的操作错误 。发现python和自动缩进有关,所以一定看好自动缩进的距离。list_to_frac([1, 2, 3, 4])结果为43/30。

使用cancel可以将生成的分式化简,frac = cancel(frac)化简为一个分数线的分式。

(a0*a1*a2*a3*a4 + a0*a1*a2 + a0*a1*a4 + a0*a3*a4 + a0 + a2*a3*a4 + a2 + a4)/(a1*a2*a3*a4 + a1*a2 + a1*a4 + a3*a4 + 1)

a0, a1, a2, a3, a4 = syms定义a0到a4,frac = apart(frac, a0)可将a0提出来。frac=1/(frac-a0)将a0去掉取倒。frac = apart(frac, a1)提出a1。

help("modules"),模块的含义,help("modules yourstr")模块中包含的字符串的意思。,

help("topics"),import os.path + help("os.path"),help("list"),help("open")

# -*- coding: UTF-8 -*-声明之后就可以在ide中使用中文注释。

定义

l = list(symbols('a0:5'))定义列表得到[a0, a1, a2, a3, a4]

fromsympyimport*

x,y,z=symbols('x y z')

init_printing(use_unicode=True)

diff(cos(x),x)求导。diff(exp(x**2), x),diff(x**4, x, x, x)和diff(x**4, x, 3)等价。

diff(expr, x, y, 2, z, 4)求出表达式的y的2阶,z的4阶,x的1阶导数。和diff(expr, x, y, y, z, 4)等价。expr.diff(x, y, y, z, 4)一步到位。deriv = Derivative(expr, x, y, y, z, 4)求偏导。但是不显示。之后用deriv.doit()即可显示

integrate(cos(x), x)积分。定积分integrate(exp(-x), (x, 0, oo))无穷大用2个oo表示。integrate(exp(-x**2-y**2),(x,-oo,oo),(y,-oo,oo))二重积分。print(expr)print的使用。

expr = Integral(log(x)**2, x),expr.doit()积分得到x*log(x)**2 - 2*x*log(x) + 2*x。

  integ.doit()和integ = Integral((x**4 + x**2*exp(x) - x**2 - 2*x*exp(x) - 2*x -

exp(x))*exp(x)/((x - 1)**2*(x + 1)**2*(exp(x) + 1)), x)连用。

limit(sin(x)/x,x,0),not-a-number表示nan算不出来,limit(expr, x, oo),,expr = Limit((cos(x) - 1)/x, x, 0),expr.doit()连用。左右极限limit(1/x, x, 0, '+'),limit(1/x, x, 0, '-')。。

Series Expansion级数展开。expr = exp(sin(x)),expr.series(x, 0, 4)得到1 + x + x**2/2 + O(x**4),,x*O(1)得到O(x),,expr.series(x, 0, 4).removeO()将无穷小移除。exp(x-6).series(x,x0=6),,得到

-5 + (x - 6)**2/2 + (x - 6)**3/6 + (x - 6)**4/24 + (x - 6)**5/120 + x + O((x - 6)**6, (x, 6))最高到5阶。

f=Function('f')定义函数变量和h=Symbol('h')和d2fdx2=f(x).diff(x,2)求2阶,,as_finite_diff(dfdx)函数和as_finite_diff(d2fdx2,[-3*h,-h,2*h]),,x_list=[-3,1,2]和y_list=symbols('a b c')和apply_finite_diff(1,x_list,y_list,0)。

Eq(x, y),,solveset(Eq(x**2, 1), x)解出来x,当二式相等。和solveset(Eq(x**2 - 1, 0), x)等价。solveset(x**2 - 1, x)

solveset(x**2 - x, x)解,solveset(x - x, x, domain=S.Reals)解出来定义域。solveset(exp(x), x)    # No solution exists解出EmptySet()表示空集。

等式形式linsolve([x + y + z - 1, x + y + 2*z - 3 ], (x, y, z))和矩阵法linsolve(Matrix(([1, 1, 1, 1], [1, 1, 2, 3])), (x, y, z))得到{(-y - 1, y, 2)}

A*x = b 形式,M=Matrix(((1,1,1,1),(1,1,2,3))),system=A,b=M[:,:-1],M[:,-1],linsolve(system,x,y,z),,solveset(x**3 - 6*x**2 + 9*x, x)解多项式。roots(x**3 - 6*x**2 + 9*x, x),得出,{3: 2, 0: 1},有2个3的重根,1个0根。solve([x*y - 1, x - 2], x, y)解出坐标。

f, g = symbols('f g', cls=Function)函数的定义,解微分方程diffeq = Eq(f(x).diff(x, x) - 2*f(x).diff(x) + f(x), sin(x))再和dsolve(diffeq,f(x))结合。得到Eq(f(x), (C1 + C2*x)*exp(x) + cos(x)/2),dsolve(f(x).diff(x)*(1 - sin(f(x))), f(x))解出来Eq(f(x) + cos(f(x)), C1),,

Matrix([[1,-1],[3,4],[0,2]]),,Matrix([1, 2, 3])列表示。M=Matrix([[1,2,3],[3,2,1]])

N=Matrix([0,1,1])

M*N符合矩阵的乘法。M.shape显示矩阵的行列数。

M.row(0)获取M的第0行。M.col(-1)获取倒数第一列。

M.col_del(0)删掉第1列。M.row_del(1)删除第二行,序列是从0开始的。M = M.row_insert(1, Matrix([[0, 4]]))插入第二行,,M = M.col_insert(0, Matrix([1, -2]))插入第一列。

M+N矩阵相加,M*N,3*M,M**2,M**-1,N**-1表示求逆。M.T求转置。

eye(3)单位。zeros(2, 3),0矩阵,ones(3, 2)全1,diag(1, 2, 3)对角矩阵。diag(-1, ones(2, 2), Matrix([5, 7, 5]))生成Matrix([

[-1, 0, 0, 0],

[ 0, 1, 1, 0],

[ 0, 1, 1, 0],

[ 0, 0, 0, 5],

[ 0, 0, 0, 7],

[ 0, 0, 0, 5]])矩阵。

Matrix([[1, 0, 1], [2, -1, 3], [4, 3, 2]])

一行一行显示,,M.det()求行列式。M.rref()矩阵化简。得到结果为Matrix([

[1, 0,  1,  3],

[0, 1, 2/3, 1/3],

[0, 0,  0,  0]]), [0, 1])。

M = Matrix([[1, 2, 3, 0, 0], [4, 10, 0, 0, 1]]),M.nullspace()

Columnspace

M.columnspace()和M = Matrix([[1, 2, 3, 0, 0], [4, 10, 0, 0, 1]])

M = Matrix([[3, -2,  4, -2], [5,  3, -3, -2], [5, -2,  2, -2], [5, -2, -3,  3]])和M.eigenvals()得到{3: 1, -2: 1, 5: 2},,This means thatMhas eigenvalues -2, 3, and 5, and that the eigenvalues -2 and 3 have algebraic multiplicity 1 and that the eigenvalue 5 has algebraic multiplicity 2.

P, D = M.diagonalize(),P得Matrix([

[0, 1, 1,  0],

[1, 1, 1, -1],

[1, 1, 1,  0],

[1, 1, 0,  1]]),,D为Matrix([

[-2, 0, 0, 0],

[ 0, 3, 0, 0],

[ 0, 0, 5, 0],

[ 0, 0, 0, 5]])

P*D*P**-1 == M返回为True。lamda = symbols('lamda')。

lamda = symbols('lamda')定义变量,p = M.charpoly(lamda)和factor(p)

expr = x**2 + x*y,srepr(expr)可以将表达式说明计算法则,"Add(Pow(Symbol('x'), Integer(2)), Mul(Symbol('x'), Symbol('y')))"。。

x = symbols('x')和x = Symbol('x')是一样的。srepr(x**2)得到"Pow(Symbol('x'), Integer(2))"。Pow(x, 2)和Mul(x, y)得到x**2。x*y

type(2)得到<class 'int'>,type(sympify(2))得到<class 'sympy.core.numbers.Integer'>..srepr(x*y)得到"Mul(Symbol('x'), Symbol('y'))"。。。

Add(Pow(x, 2), Mul(x, y))得到"Add(Mul(Integer(-1), Pow(Symbol('x'), Integer(2))), Mul(Rational(1, 2), sin(Mul(Symbol('x'), Symbol('y')))), Pow(Symbol('y'), Integer(-1)))"。。Pow函数为幂次。

expr = Add(x, x),expr.func。。Integer(2).func,<class 'sympy.core.numbers.Integer'>,,Integer(0).func和Integer(-1).func,,,expr = 3*y**2*x和expr.func得到<class 'sympy.core.mul.Mul'>,,expr.args将表达式分解为得到(3, x, y**2),,expr.func(*expr.args)合并。expr == expr.func(*expr.args)返回True。expr.args[2]得到y**2,expr.args[1]得到x,expr.args[0]得到3.。

expr.args[2].args得到(y, 2)。。y.args得到空括号。Integer(2).args得到空括号。

from sympy import *

E**(I*pi)+1,可以看出,I和E,pi已将在sympy内已定义。

x=Symbol('x'),,expand( E**(I*x) )不能展开,expand(exp(I*x),complex=True)可以展开,得到I*exp(-im(x))*sin(re(x)) + exp(-im(x))*cos(re(x)),,x=Symbol("x",real=True)将x定义为实数。再展开expand(exp(I*x),complex=True)得到。I*sin(x) + cos(x)。。

tmp = series(exp(I*x), x, 0, 10)和pprint(tmp)打印出来可读性好,print(tmp)可读性不好。。pprint将公式用更好看的格式打印出来,,pprint( series( cos(x), x, 0, 10) )

integrate(x*sin(x), x),,定积分integrate(x*sin(x), (x, 0, 2*pi))。。

用双重积分求解球的体积。

x, y, r = symbols('x,y,r')和2 * integrate(sqrt(r*r-x**2), (x, -r, r))计算球的体积。计算不来,是因为sympy不知道r是大于0的。r = symbols('r', positive=True)这样定义r即可。circle_area=2*integrate(sqrt(r**2-x**2),(x,-r,r))得到。circle_area=circle_area.subs(r,sqrt(r**2-x**2))将r替换。

integrate(circle_area,(x,-r,r))再积分即可。

expression.sub([(x,y),(y,x)])又换到原来的状况了。

expression.subs(x, y),,将算式中的x替换成y。。

expression.subs({x:y,u:v}) : 使用字典进行多次替换。。

expression.subs([(x,y),(u,v)]) : 使用列表进行多次替换。。

import numpy as np

import cv2 as cv

face_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml')

eye_cascade = cv.CascadeClassifier('haarcascade_eye.xml')

img = cv.imread('sachin.jpg')

gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.3, 5)

for (x,y,w,h) in faces:

cv.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

roi_gray = gray[y:y+h, x:x+w]

roi_color = img[y:y+h, x:x+w]

eyes = eye_cascade.detectMultiScale(roi_gray)

for (ex,ey,ew,eh) in eyes:

cv.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

cv.imshow('img',img)

cv.waitKey(0)

Python发展至今,已经有越来越多的人使用python进行科学技术,NumPY是python中的一款高性能科学计算和数据分析的基础包。

ndarray

ndarray(以下简称数组)是numpy的数组对象,需要注意的是,它是同构的,也就是说其中的所有元素必须是相同的类型。其中每个数组都有一个shape和dtype。

shape既是数组的形状,比如

复制代码

1 import numpy as np

2 from numpy.random import randn

3

4 arr = randn(12).reshape(3, 4)

5

6 arr

7

8 [[ 0.98655235 1.20830283 -0.72135183 0.40292924]

9 [-0.05059849 -0.02714873 -0.62775486 0.83222997]

10 [-0.84826071 -0.29484606 -0.76984902 0.09025059]]

11

12 arr.shape

13 (3, 4)

复制代码

其中(3, 4)即代表arr是3行4列的数组,其中dtype为float64

一下函数可以用来创建数组

array将输入数据转换为ndarray,类型可制定也可默认

asarray将输入转换为ndarray

arange类似内置range

ones、ones_like根据形状创建一个全1的数组、后者可以复制其他数组的形状

zeros、zeros_like类似上面,全0

empty、empty_like创建新数组、只分配空间

eye、identity创建对角线为1的对角矩阵

数组的转置和轴对称

转置是多维数组的基本运算之一。可以使用.T属性或者transpose()来实现。.T就是进行轴对换而transpose则可以接收参数进行更丰富的变换

复制代码

arr = np.arange(6).reshape((2,3))

print arr

[[0 1 2]

[3 4 5]]

print arr.T

[[0 3]

[1 4]

[2 5]]

arr = np.arange(24).reshape((2,3,4))

print arr

[[[ 0 1 2 3]

[ 4 5 6 7]

[ 8 9 10 11]]

[[12 13 14 15]

[16 17 18 19]

[20 21 22 23]]]

print arr.transpose((0,1,2))

[[[ 0 1 2 3]

[ 4 5 6 7]

[ 8 9 10 11]]

[[12 13 14 15]

[16 17 18 19]

[20 21 22 23]]]

复制代码

数组的运算

大小相等的数组之间做任何算术运算都会将运算应用到元素级别。

复制代码

1 arr = np.arange(9).reshape(3, 3)

2 print arr

3

4 [[0 1 2]

5 [3 4 5]

6 [6 7 8]]

7

8 print arr*arr

9

10 [[ 0 1 4]

11 [ 9 16 25]

12 [36 49 64]]

13

14 print arr+arr

15

16 [[ 0 2 4]

17 [ 6 8 10]

18 [12 14 16]]

19

20 print arr*4

21

22 [[ 0 4 8]

23 [12 16 20]

24 [24 28 32]]

复制代码

numpy的简单计算中,ufunc通用函数是对数组中的数据执行元素级运算的函数。

如:

复制代码

arr = np.arange(6).reshape((2,3))

print arr

[[0 1 2]

[3 4 5]]

print np.square(arr)

[[ 0 1 4]

[ 9 16 25]]

复制代码

类似的有:abs,fabs,sqrt,square,exp,log,sign,ceil,floor,rint,modf,isnan,isfinite,isinf,cos,cosh,sin,sinh,tan,tanh,

add,subtract,multiply,power,mod,equal,等等