sympy subs
时间: 2023-10-24 20:26:55 浏览: 194
Sympy subs function is used to substitute one or more symbols or expressions with new symbols or values in a given expression. It stands for "substitute".
For example, let's say we have an expression `x**2 + y**2` and we want to substitute `x` with `2` and `y` with `3`. We can do this using the subs function like this:
```python
from sympy import Symbol, subs
x = Symbol('x')
y = Symbol('y')
expr = x**2 + y**2
new_expr = subs(expr, [(x, 2), (y, 3)])
print(new_expr)
```
The output will be `13`, as the expression `x**2 + y**2` is now evaluated with `x=2` and `y=3`.
相关问题
sympy中F.subs
sympy中的F.subs()是一个方法,用于将表达式中的变量替换为给定的值。它接受一个字典作为参数,其中字典的键是要替换的变量,其对应的值是要替换的新值。
例如,如果我们有以下表达式:
```
x = symbols('x')
expr = x**2 + 2*x + 1
```
我们可以使用F.subs()方法将变量x替换为3:
```
expr.subs({x: 3})
```
这将返回10,因为3的平方是9,加上2乘以3再加1等于10。
#外点法(能运行出来) import math import sympy import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D plt.ion() fig = plt.figure() ax = Axes3D(fig) def draw(x,index,M): # F = f + MM * alpha # FF = sympy.lambdify((x1, x2), F, 'numpy') Z = FF(*(X, Y,M)) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='rainbow',alpha=0.5) ax.scatter(x[0], x[1], FF(*(x[0],x[1],M)), c='r',s=80) ax.text(x[0], x[1], FF(*(x[0],x[1],M)), 'here:(%0.3f,%0.3f)' % (x[0], x[1])) ax.set_zlabel('F') # 坐标轴 ax.set_ylabel('X2') ax.set_xlabel('X1') plt.pause(0.1) # plt.show() # plt.savefig('./image/%03d' % index) plt.cla() C = 10 # 放大系数 M = 1 # 惩罚因子 epsilon = 1e-5 # 终止限 x1, x2 = sympy.symbols('x1:3') MM=sympy.symbols('MM') f = -x1 + x2 h = x1 + x2 - 1 # g=sympy.log(x2) if sympy.log(x2)<0 else 0 g = sympy.Piecewise((x2-1, x2 < 1), (0, x2 >= 1)) # u=lambda x: alpha = h ** 2 + g ** 2 F = f + MM * alpha # 梯度下降来最小化F def GD(x,M,n): # F = f + M * alpha # delta_x = 1e-11 # 数值求导 # t = 0.0001 # 步长 e = 0.001 # 极限 # my_print(e) np.array(x) for i in range(15): t = sympy.symbols('t') grad = np.asarray( [sympy.diff(F, x1).subs([(x1, x[0]), (x2, x[1]),(MM,M)]), sympy.diff(F, x2).subs([(x1, x[0]), (x2, x[1]),(MM,M)])]) # print('g',grad) # print((x-t*grad)) # print(F.subs([(x1,(x-t*grad)[0]),(x2,(x-t*grad)[1])])) t = sympy.solve(sympy.diff(F.subs([(x1, (x - t * grad)[0]), (x2, (x - t * grad)[1]),(MM,M)]), t), t) print('t',t) x = x - t * grad print('x', x) # print('mmm',M) draw(x,n*10+i,M) # my_print(np.linalg.norm(grad)) # print(type(grad)) if (abs(grad[0]) < e and abs(grad[1]) < e): # print(np.linalg.norm(grad)) print('g', grad) break return list(x) pass x = [-0.5, 0.2] X = np.arange(0, 4, 0.25) Y = np.arange(0, 4,
0.25) # 定义网格点坐标 X, Y = np.meshgrid(X, Y) # 生成网格点 FF = sympy.lambdify((x1, x2,MM), F, 'numpy') # 将表达式转化为可计算的函数 draw(x,0,M) # 绘制函数图像 for i in range(5): # 迭代次数为5次 x = GD(x,M,i) # 梯度下降求解极小值 M = C * M # 更新惩罚因子 print('M',M) # plt.savefig('./image/%03d' % index) plt.ioff() plt.show()
这是一个使用外点法求解带约束非线性规划问题的 Python 代码,其中 F 为目标函数,alpha 为罚函数,x1, x2 为自变量,MM 为惩罚因子。函数 GD 为梯度下降求解极小值。代码中还包含了绘制函数图像的 draw 函数。
阅读全文