Skip to main content
 首页 » 编程设计

python之用python/sympy解决RC电路

2024年10月25日10lovecherry

我正在独立完成 Mark Newman 的《计算物理学》一书,具体来说是练习 6.5(可以下载 here)。该问题是求解由复指数源电压驱动的 RC 电路中的节点电压。

我想做的是将我的节点方程式变成 Av = B 的形式。这是我目前所做的。

import numpy as np 
import sympy 
 
# Define constants 
R1=R3=R5 = 1e3 
R2=R4=R6 = 2e3 
C1 = 1e-6 
C2 = 0.5e-6 
x_plus = 3 
x_minus = 0 
w = 1000 
 
# Define relations 
V_plus = sympy.symbols('V_plus') 
t = sympy.symbols('t') 
 
V_plus = x_plus*sympy.exp(1j*w*t) 
V_minus = 0 
 
V1,V2,V3 = sympy.symbols('V1 V2 V3') 
 
V1_eqn = (V1-V_plus)/R1 + (V1-V2)/(1/(1j*w*C1)) + (V1-V_minus)/R4 
V2_eqn = (V2-V_plus)/R2 + (V2-V1)/(1/(1j*w*C1)) + (V2-V_minus)/R5 + (V2-V3)/(1/(1j*w*C2)) 
V3_eqn = (V3-V_plus)/R3 + (V3-V2)/(1/(1j*w*C2)) + (V3-V_minus)/R6 
 
# Prepare 
V = [V1,V2,V3] 
V_vec = np.matrix(V) 
 
A = np.matrix([ 
    [V1_eqn.expand().coeff(x) for x in V], 
    [V2_eqn.expand().coeff(x) for x in V], 
    [V3_eqn.expand().coeff(x) for x in V] 
    ]) 
print(A) 

现在,我遇到的问题是提取三个方程的常数项,以便我可以将它们加载到 B 中。除其他事项外,其中一个问题是“常数项”实际上并不是常数。它是“t”的复杂指数函数。由于这是笔和纸的一个相当简单的问题,我确切地知道常数项会是什么样子,所以我可以提取它。不过,我的目标是以一种不需要知道答案的方式解决这个问题;)。

我考虑过的一种方法是取每个方程并减去我已经放入 Av 中的所有项,但这似乎有点草率而且不是很 pythonic。有谁知道一种更好的方法来提取技术上不恒定的常数项?谢谢。

请您参考如下方法:

除了一些符号上的快捷方式外,减去您已经放入 A 中的项正是您应该而且必须做的。

这是一个稍微短一点的版本:

import sympy 
 
# Define constants 
R1=R3=R5 = 1e3 
R2=R4=R6 = 2e3 
C1 = 1e-6 
C2 = 0.5e-6 
x_plus = 3 
x_minus = 0 
w = 1000 
 
# Define relations 
V_plus = sympy.symbols('V_plus') 
t = sympy.symbols('t') 
 
V_plus = x_plus*sympy.exp(1j*w*t) 
V_minus = 0 
 
V1,V2,V3 = sympy.symbols('V1 V2 V3') 
 
# Using a matrix to collect all equations allows you to use a matrix-vector-product below 
eqns = sympy.matrices.Matrix([ 
    (V1-V_plus)/R1 + (V1-V2)/(1/(1j*w*C1)) + (V1-V_minus)/R4, 
    (V2-V_plus)/R2 + (V2-V1)/(1/(1j*w*C1)) + (V2-V_minus)/R5 + (V2-V3)/(1/(1j*w*C2)), 
    (V3-V_plus)/R3 + (V3-V2)/(1/(1j*w*C2)) + (V3-V_minus)/R6 
]) 
 
# Prepare 
V = [V1,V2,V3] 
V_vec = sympy.matrices.Matrix(V) 
 
# The "or 0" does nothing if there are coefficients y in x, but if there aren't, it replaced 
# the "None" with "0". This again is required for using A * V_vec below 
A = sympy.matrices.Matrix([ [ x.expand().coeff(y) or 0 for y in V ] for x in eqns ]) 
 
print(A) 
 
remainder = (eqns - A * V_vec) 
remainder.simplify() 
print remainder