Skip to main content
 首页 » 编程设计

Python:四阶龙格-库塔法

2025年05月04日19myhome

from math import sin 
from numpy import arange 
from pylab import plot,xlabel,ylabel,show 
def answer(): 
    print('Part a:') 
    print(low(x,t)) 
    print('First Graph') 
    print('') 
 
 
def low(x,t): 
    return 1/RC * (V_in - V_out) 
 
a = 0.0 
b = 10.0 
N = 1000 
h = (b-a)/N 
RC = 0.01 
V_out = 0.0 
 
tpoints = arange(a,b,h) 
xpoints = [] 
x = 0.0 
 
for t in tpoints: 
    xpoints.append(x) 
    k1 = h*f(x,t) 
    k2 = h*f(x+0.5*k1,t+0.5*h) 
    k3 = h*f(x+0.5*k2,t+0.5*h) 
    k4 = h*f(x+k3,t+h) 
    x += (k1+2*k2+2*k3+k4)/6 
 
plot(tpoints,xpoints) 
xlabel("t") 
ylabel("x(t)") 
show() 

所以我对四阶龙格库塔方法进行了编码,但我试图适应的部分是问题所在,如果 [2t] 是偶数,则 V_in(t) = 1,如果 [2t] 是奇数,则为 -1。

另外,我不确定我是否应该返回这个等式: 返回 1/RC * (V_in - V_out)

问题是:

Problem 8.1

如果你能帮助我,我将不胜感激!

请您参考如下方法:

So I have the fourth order runge kutta method coded but the part I'm trying to fit in is where the problem say V_in(t) = 1 if [2t] is even or -1 if [2t] is odd.

您将 V_in 视为常量。问题说它是一个函数。所以一个解决方案是使它成为一个函数!这是一个非常简单的函数:

def dV_out_dt(V_out, t) : 
    return (V_in(t) - V_out)/RC 
 
def V_in(t) : 
    if math.floor(2.0*t) % 2 == 0 : 
        return 1 
    else : 
        return -1 

您不需要也不希望在 V_in(t) 的定义中使用 if 语句。循环内的分支是昂贵的,并且该函数将在循环内多次调用。有一种简单的方法可以避免这种 if 语句。

def V_in(t) : 
    return 1 - 2*(math.floor(2.0*t) % 2) 

这个函数很小,你可以把它折叠成导数函数:

def dV_out_dt(V_out, t) : 
    return ((1 - 2*(math.floor(2.0*t) % 2)) - V_out)/RC