[PYTHON MATRIX-SIG] A fix for mrange

Perry A. Stoll stoll@atr-sw.atr.co.jp
Tue, 30 Jan 1996 11:57:23 +0900



>>> Numeric.mrange(1,5,1,'i')
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File "/home/stoll/Python/1.3/lib/python/numeric/Numeric.py", line 64, in mrange
    return m*step + start
TypeError: cannot perform this operation on these types
>>> Numeric.mrange(1,5,0.5,'f')
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File "/home/stoll/Python/1.3/lib/python/numeric/Numeric.py", line 64, in mrange
    return m*step + start
TypeError: cannot perform this operation on these types

>>> Numeric.mrange(1,5,1.0,'l')
array([1.0,2.0,3.0,4.0], 'd')


Shouldn't mrange honor the typecode?

How about this as a replacement for mrange:

# ???default typecode to long int to match builtin range()???
def mrange(start, stop=None, step=1, typecode='l'):
	"""Just like range() except it returns an array whose
	type can be specfied by the keyword argument typecode.
	"""

	if (stop == None):
		stop = start
		start = 0
	n = int(math.ceil(float(stop-start)/step))
 	m = array(range(n), 'l')*step + start
 	if (m.typecode() != typecode):
 	     m = m.cast(typecode)
 	return m


Now I get this:
>>> Numeric.mrange(1,5,1,'i')
array([1,2,3,4], 'i')
>>> Numeric.mrange(1,5,1.0,'l')
array([1,2,3,4], 'l')
>>> Numeric.mrange(200,300,10,'b')
array([200,210,220,230,240,250,4,14,24,34], 'b')
>>> Numeric.mrange(1,5,0.25,'l')
array([1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4], 'l')

The last is a little weird, but mrange always honors the typecode,
which I think is very important. When I specify a type, I expect an
array of that type.

To coerce or not to coerce, that is the question...

-Perry

=================
MATRIX-SIG  - SIG on Matrix Math for Python

send messages to: matrix-sig@python.org
administrivia to: matrix-sig-request@python.org
=================