Friday, September 21, 2012

Simple array math

Okay, this is embarassing, but I'm owning up to it.  It took me a while to figure out how to get python to do something that IDL does intuitively:  math on arrays. For example, let's redshift some emission lines:
IDL> zz = 3.14 
IDL> waves = [4959., 5007., 6563.]
IDL> print, waves * (1.0+zz)
      20530.3      20729.0      27170.8
Try guessing the equivalent in python, and you get yelled at:
TypeError                                 Traceback (most recent call last)

/Volumes/Apps_and_Docs/jrrigby1/<ipython console> in <module>()

TypeError: unsupported operand type(s) for /: 'list' and 'float'

My student Alice, as usual, showed me the solution:
In [3]: from numpy import array
In [4]: zz  = 3.14
In [6]: wave = array([4959, 5007, 6563])
In [7]: print wave * (1.0+zz)
[ 20530.26  20728.98  27170.82]
See those stupid square brackets?  They're not optional:
wave = array([foo, bar, foo])

No comments:

Post a Comment