[Numpy-discussion] Piecewise functions.

Paulo J. S. Silva pjssilva at ime.usp.br
Fri Sep 23 06:34:19 EDT 2005


Here is a slightly different solution, that is easier to my eyes and
that can handle arguments in arbitrary order. 

It requires numarray (as it uses array indexing). If I understand well
it should work woth the new scipy-core (Numeric3), but I haven't it
compiled here.

Obs: Probably f2 implementation is faster than f1.

Best,

Paulo

----

from numarray import *

def f1(x):
    """Implementation of:
    -1/(x-pi) for x < pi
    1/(x-pi) for x > pi
    """
    result = zeros(len(x), x.typecode())

    # First solution, probably slower, but clear.
    result[x < pi] = -1/(x[x < pi]-pi)
    result[x > pi] = 1/(x[x > pi]-pi)
    return result

def f2(x):
    """Second Iplementation of:
    -1/(x-pi) for x < pi
    1/(x-pi) for x > pi
    """
    result = zeros(len(x), x.typecode())

    # Second solution, probably faster as where returns only
    # the correct indexes.
    small = where(x < pi)
    big = where(x > pi)
    result[small] = -1/(x[small]-pi)
    result[big] = 1/(x[big]-pi)
    return result

x = arange(0, 10, 1, Float)
print f1(x)
print f2(x)
print abs(1/(x-pi))

# It uses the default value for pi.
api = array([pi])
print f1(api)
print f2(api)







More information about the NumPy-Discussion mailing list