简体   繁体   中英

Python: Fourth Order Runge-Kutta Method

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

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.

Also the I'm not sure if I'm suppose to return this equation: return 1/RC * (V_in - V_out)

Here is the problem:

Problem 8.1

It would be greatly appreciated if you help me out!

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.

You are treating V_in as a constant. The problem says that it's a function. So one solution is to make it a function! It's a very simple function to write:

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

You don't need or want that if statement in the definition of V_in(t) . A branch inside of a loop is expensive, and this function will be called many times from inside a loop. There's a simple way to avoid that if statement.

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

This function is so small that you can fold it into the derivative function:

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

The function should look something like this:

def f(x,t):
    V_out = x
    n = floor(2*t)
    V_in = (1==n%2)? -1 : 1
    return 1/RC * (V_in - V_out)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM