CCL Home Page
Up Directory CCL umath
# This file is a crude replacement for the umath module
# that comes with the numerics package. Use it only
# if you do not have this package. This version implements
# just the standard math functions for objects of arbitrary
# types; it does not have any array functions. Note also
# that it is a lot slower than the real "umath".
#
# For those who don't know anything about umath:
# umath provides "universal math" functions for all types.
# Python comes with a module "math" that offers the standard
# math functions for floating-point numbers. But suppose you
# define your own numeric type (complex numbers, automatic
# derivatives, arrays, etc.). You can of course define
# analogous functions for your new type, but then you
# effectively have a *different* function to call for each
# type (because they come from different modules). Which means
# you can't write code that works for all types that support
# a given set of functions.
# umath provides the solution: When you call one of the
# functions from umath, it first checks whether it "knows"
# the type of the argument, and then it calls the appropriate
# function. For any other type, it calls a method with the
# same name. For example, if "x" is an object of a new
# type defined as a Python class, then "sqrt(x)" gets
# translated into "x.sqrt()". This enables all new classes
# to provide their own implementation for these functions.
# The "real" umath from the numerics package knows about
# integers, floats, complex numbers, and arrays of these
# objects. This stripped-down (and slowed-down) version
# knows only integers and floats
#
# Written by: Konrad Hinsen 
# Last revision: 1996-1-30
# 

import math, types

class _umathfunc:

    def __init__(self, mathfunc, name):
	self.mathfunc = mathfunc
	self.name = name

    def __call__(self, arg):
	t = type(arg)
	if t == types.IntType or t == types.FloatType:
	    return self.mathfunc(arg)
	else:
	    return getattr(arg, self.name)()

acos = _umathfunc(math.acos, "acos")
asin = _umathfunc(math.asin, "asin")
atan = _umathfunc(math.atan, "atan")
cos = _umathfunc(math.cos, "cos")
cosh = _umathfunc(math.cosh, "cosh")
exp = _umathfunc(math.exp, "exp")
fabs = _umathfunc(math.fabs, "fabs")
log = _umathfunc(math.log, "log")
log10 = _umathfunc(math.log10, "log10")
pow = _umathfunc(math.pow, "pow")
sin = _umathfunc(math.sin, "sin")
sinh = _umathfunc(math.sinh, "sinh")
sqrt = _umathfunc(math.sqrt, "sqrt")
tan = _umathfunc(math.tan, "tan")
tanh = _umathfunc(math.tanh, "tanh")

e = math.e
pi = math.pi
Modified: Tue Jan 30 17:00:00 1996 GMT
Page accessed 8480 times since Sat Apr 17 21:35:46 1999 GMT