passing objects to functions

Joe Heafner heafnerj at spam.vnet.net
Sun Nov 24 15:15:25 EST 2002


I have the following Python code written using VPython:

from visual import *

def derivative(t,x,xp,xpp):
  xmu = 1.407645794e16
  r = mag(x)
  r3 = r**3
  xpp[0] = -xmu*x[0]/r3
  xpp[1] = -xmu*x[1]/r3
  xpp[2] = -xmu*x[2]/r3

t = 2451545.0
x=vector(1.,1.,1.)
xdot=vector(1.,1.,1.)
xmu = 1.407645794e16
#xddot = -xmu*x/(mag(x)**3)
#print xddot
xddot=vector(0,0,0)

x=vector(2.,2.,2.)
derivative(t,x,xdot,xddot)

print xddot

When executed, I get the expected result for xddot. When I modify the code 
to read:

from visual import *

def derivative(t,x,xp,xpp):
  xmu = 1.407645794e16
  r = mag(x)
  r3 = r**3
  #xpp[0] = -xmu*x[0]/r3
  #xpp[1] = -xmu*x[1]/r3
  #xpp[2] = -xmu*x[2]/r3
  xpp = -xmu*x/r3

t = 2451545.0
x=vector(1.,1.,1.)
xdot=vector(1.,1.,1.)
xmu = 1.407645794e16
#xddot = -xmu*x/(mag(x)**3)
#print xddot
#xddot=vector(0,0,0)

x=vector(2.,2.,2.)
derivative(t,x,xdot,xddot)

print xddot

I get the error message:

[localhost:~] joe% python testrk4.py
Visual-2002-07-22
Traceback (most recent call last):
File "testrk4.py", line 22, in ?
derivative(t,x,xdot,xddot)
NameError: name 'xddot' is not defined
[localhost:~] joe%

Why does this not work when simply writing

xddot = -xmu*x/(mag(x)**3)

outside my function works perfectly? I'm lost here, and Lutz and Ascher's 
book has not helped me, most probably because I don't know where to look 
for the problem I'm having. I'm trying to port some QuickBASIC numerical 
analysis code and I need  the capability to pass a vector (a VPython 
vector, not an ordinary array) into a function, potentially modify that
vector's components, and then have the same vector accessible outside the 
function. I can make it work with arrays but not with vectors. I'd 
appreciate any help.

JH




More information about the Python-list mailing list