首页 文章

python scipy odeint返回值

提问于
浏览
0

我一直在玩scipy中的odeint,我无法理解函数返回的值是什么 . 例如,

# -*- coding: utf-8 -*-
"""
Created on Sat Feb 04 20:01:16 2017

@author: Esash
"""

from scipy.integrate import odeint
import matplotlib.pyplot as plt
import numpy as np

def MassSpring(state,t):
  # unpack the state vector
  x = state[0]
  xd = state[1]

  # these are our constants
  k = -5.5 # Newtons per metre
  m = 1.5 # Kilograms
  g = 9.8 # metres per second

  # compute acceleration xdd
  xdd = ((k*x)/m) + g

  # return the two state derivatives
  return [xd, xdd]

state0 = [0.0, 0.0]
t = np.arange(0.0, 10.0, 0.1)

state = odeint(MassSpring, state0, t)

plt.plot(t, state)
plt.xlabel('TIME (sec)')
plt.ylabel('STATES')
plt.title('Mass-Spring System')
plt.legend(('$x$ (m)', '$\dot{x}$ (m/sec)'))

在上面的代码中,我将两个参数设置为0.0和0.0,函数中的xd只是0.0,我也返回 . 但是返回值不仅仅是0.0,而是变化的 .

In [14]: state
Out[14]: 
array([[ 0.        ,  0.        ],
       [ 0.04885046,  0.97402207],
       [ 0.19361613,  1.91243899],
       ..., 
       [ 0.10076832, -1.39206172],
       [ 0.00941998, -0.42931942],
       [ 0.01542821,  0.54911655]])

此外,如果我有一个微分方程式,我需要发送许多参数,那么我不能在odeint调用中将M参数作为列表或元组发送,并仅将ODE的解决方案作为单个数组返回 . 它期望发送的参数数量应该等于函数返回的参数数量 . 为什么是这样?

我无法理解这个功能是如何工作的 . 有人可以向我解释一下吗?如果我听起来太混乱,我道歉 .

非常感谢 .

1 回答

  • 1

    我无法理解函数作为返回值返回的内容 .

    odeint 的返回值是请求时间值的计算解 . 也就是说,在这个电话之后

    state = odeint(MassSpring, state0, t)
    

    state[0] 是[x(t [0]),x'(t [0])], state[1] 是[x(t [1]),x'(t [1])]等 . 如果你想绘图只是 x 坐标,您可以调用 plt.plot(t, state[:, 0]) 绘制 state 的第一列 .

    我已将两个参数设置为0.0和0.0 [...]

    您所谓的"parameters"通常被称为初始条件 . 它们是t = 0时x(t)和x'(t)的值 .

    但是返回值不仅仅是0.0,而是变化的 .

    那是因为(0,0)不是系统的 balancer . 看看等式

    xdd = ((k*x)/m) + g
    

    x 为0时,您得到 xdd = g ,因此 xdd 最初是正数 . 也就是说,存在作用在质量上的非零力(重力),因此它会加速 .

    balancer 状态是[-g * m / k,0] .

    另外,如果我有一个微分方程式,我需要发送许多参数,那么我不能将odeint调用中的M个参数作为列表或元组发送,只返回ODE的解决方案作为单个数组 . 它期望发送的参数数量应该等于函数返回的参数数量 . 为什么是这样?

    odeint 一次仅解决一组初始条件的系统问题 . 如果要生成多个解决方案(对应于不同的初始条件),则必须多次调用 odeint .

相关问题