简体   繁体   中英

Values Within range of if statement not printing (Runge-Kutta Fourth Order in Python)

I am writing a code to perform a Fourth Order Runge-Kutta numerical approximation with adaptive step size.

def f(x, t):       #integrating function
    return -x

def exact(t):       #exact solution
    return np.exp(-t)

def Rk4(x0, t0, dt):      #Runge-Kutta Fourth Order
    t = np.arange(0, 1+dt, dt)
    n = len(t)
    x = np.array([x0]*n)
    x[0],t[0] = x0,t0
    for i in range(n-1):
        h = t[i+1]-t[i]
        k1 = h*f(x[i], t[i])
        k2 = h*f(x[i] + c21*k1, t[i] + c20*h)
        k3 = h*f(x[i] + c31*k1 + c32*k2, t[i] + c30*h)
        k4 = h*f(x[i] + c41*k1 + c42*k2 + c43*k3, t[i] + c40*h)
        k5 = h*f(x[i] + c51*k1 + c52*k2 + c53*k3 + c54*k4, t[i] + c50*h)
        k6 = h*f(x[i] + c61*k1 + c62*k2 + c63*k3 + c64*k4 + c65*k5, t[i] + c60*h)
        x[i+1] = x[i] + a1*k1 + a3*k3 + a4*k4 + a5*k5
        x5 = x[i] + b1*k1 + b3*k3 + b4*k4 + b5*k5 + b6*k6
    E = abs(x[n-1]-exact(t[n-1]))     #error
    print(E)
    if E < 10^-5:     #error tolerance
        return x[n-1]      #approximation

print("For dt = 10e-2, x(1) =",Rk4(1.0,0.0,10e-2))
print("For dt = 10e-3, x(1) =",Rk4(1.0,0.0,10e-3))

However, when I run the code, it prints:

5.76914409023e-08
For dt = 10e-2, x(1) = None
4.8151482801e-12
For dt = 10e-3, x(1) = None

Therefore the error, E, is less than 10^-5 in both cases, yet it doesn't print x(1).

^ is bitwise exclusive or in Python, not exponentiation; that's ** . So 10^-5 (10 xor -5) is -15, and none of your errors is less than -15.

You probably want the scientific notation constant 1e-5 or, if you want to write it as an actual exponentiation operation, 10 ** -5 .

For those concerned with performance: the expression using ** is actually compiled to a constant when Python loads the script, since the arguments are both constants, so it won't have any performance impact to write it that way. :-)

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