尝试使用欧拉方法求解数值Diff Eq,无效值误差

时间:2016-10-16 07:04:52

标签: python numpy matplotlib numerical-methods

我正试图从这个网站上学习:http://nbviewer.jupyter.org/github/numerical-mooc/numerical-mooc/blob/master/lessons/01_phugoid/01_03_PhugoidFullModel.ipynb

我试图用尽可能少的帮助来编写它,但我一直收到这个错误:

C:\ Users \"我的真实姓名" \ Anaconda2 \ lib \ site-packages \ ipykernel__main __。py:29:RuntimeWarning:double_scalars中遇到无效值

我的情节上没有数据点。所以我直接从网站上粘贴了所有代码,我仍然得到错误!我放弃了,有人可以帮助一个蟒蛇新手吗?

import numpy as np
from matplotlib import pyplot
from math import sin, cos, log, ceil
%matplotlib inline
from matplotlib import rcParams
rcParams['font.family'] = 'serif'
rcParams['font.size'] = 16

# model parameters:
g = 9.8      # gravity in m s^{-2}
v_t = 30.0   # trim velocity in m s^{-1}   
C_D = 1/40  # drag coefficient --- or D/L if C_L=1
C_L = 1   # for convenience, use C_L = 1

### set initial conditions ###
v0 = v_t     # start at the trim velocity (or add a delta)
theta0 = 0 # initial angle of trajectory
x0 = 0     # horizotal position is arbitrary
y0 = 1000  # initial altitude



def f(u):

    v = u[0]
    theta = u[1]
    x = u[2]
    y = u[3]
    return np.array([-g*sin(theta) - C_D/C_L*g/v_t**2*v**2, -g*cos(theta)/v + g/v_t**2*v, v*cos(theta), v*sin(theta)])

def euler_step(u, f, dt):
    u + dt * f(u)

T = 100                          # final time
dt = 0.1                           # time increment
N = int(T/dt) + 1                  # number of time-steps
t = np.linspace(0, T, N)      # time discretization

# initialize the array containing the solution for each time-step
u = np.empty((N, 4))
u[0] = np.array([v0, theta0, x0, y0])# fill 1st element with initial values

# time loop - Euler method
for n in range(N-1):
    u[n+1] = euler_step(u[n], f, dt)





x = u[:,2]
y = u[:,3]


pyplot.figure(figsize=(8,6))
pyplot.grid(True)
pyplot.xlabel(r'x', fontsize=18)
pyplot.ylabel(r'y', fontsize=18)
pyplot.title('Glider trajectory, flight time = %.2f' % T, fontsize=18)
pyplot.plot(x,y, 'k-', lw=2);

1 个答案:

答案 0 :(得分:0)

解决方案非常简单。你忘记了euler_step中的return语句。 变化

def euler_step(u, f, dt):
    u + dt * f(u)

def euler_step(u, f, dt):
    return u + dt * f(u)

它会起作用