【问题标题】:Code not working (python) [closed]代码不起作用(python)[关闭]
【发布时间】:2014-02-28 19:50:37
【问题描述】:
import scipy as sp
import numpy as np
import pylab as pl
import scipy.integrate as spi
import matplotlib.pyplot as plt


G=6.67*10**(-11)
M=6.4*(10**23)
R=3.4*(10**6)
m=260
#define the gravitational constant G, radius (R) and mass (M) of Mars and the mass of the satellite (m)

#called with the variables to be differentiated
def f(a,t):
  xx=a[0]
  vx=a[1]
  yy=a[2]
  vy=a[3]
  ax=-(G*M*xx)/((xx**2+yy**2)**1.5)
  ay=(-G*M*yy)/((xx**2+yy**2)**1.5)
  return [vx,ax,vy,ay]
#returns differentiated values, function defines values and returns new values

d=((xx**2+yy*2)**(0.5))

if d<r:
    vx,vy,ax,ay=0,0,0,0
    return [vx,ax,vy,ay]

#first initial conditions- blue curve

t1=sp.linspace(0.,259200,10000) #three years

initial1=[3*R,2000,3*R,500]

solution1=spi.odient(f,initial1,t1)

x1=solution1[:,0]
y1=solution1[:,2]

pl.figure(1)
pl.plot(x1,y1)
pl.xlabel("x")
pl.ylabel("y")
pl.show()

您好,请您帮我运行这段代码!它是用 python 编写的,相当基本,第二个返回函数有一个错误,它说“返回”外部函数。另一个错误是“'module'对象没有属性'odient'”。

【问题讨论】:

  • 因为...它不在函数中?
  • 您的格式不正确,您肯定是在函数之外调用 return。
  • 我不是在解决你的问题。我只想指出,表达常数的一种更简单(更少计算)的方法是使用科学记数法,例如 G = 6.67e-11M = 6.4e23
  • ... 方法应该是odeint,而不是odient
  • 您能编辑一下您的标题吗? “代码不起作用”不会帮助任何需要与您找到相同答案的人。

标签: python scipy


【解决方案1】:
if d<r:
    vx,vy,ax,ay=0,0,0,0
    return [vx,ax,vy,ay]

这不是一个函数,所以你不能使用return。如果您想将这些值添加到列表中,您可以创建一个新列表:

new_list = [vx,ax,vy,ay]

您不需要在函数之外使用 return,因为这些变量已经在作用域内。当您在函数中使用变量时,它们与程序的其余部分不在同一范围内。例如:

>>> def foo():
        a =10
>>> a = 1
>>> foo()
>>> a
1

函数内部的a 不会影响外部的a。在您的if 语句中,您不需要return,因为它在同一范围内。变量的赋值不需要从任何地方返回,因为它是相同的范围。

正如@Hugh Bothwell 指出的,你的函数调用中有一个错字应该是:

scipy.integrate.odeint()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-01
    • 2015-03-04
    • 2015-12-24
    • 2021-08-27
    • 2013-10-11
    • 2016-12-05
    • 1970-01-01
    相关资源
    最近更新 更多