Cristóvão wrote :

I propose a generic function mapexpression in order operate in the tree of the expression. You can use it over leaf (ie the numbers or the variables) or over functions (by the fctfct parameter)

I like this function because we can use this same function for numerical transforms (for Christavo)
and rewrite rules (with trigonometric rules).

There are 2 fuzzy cases for operator add and mul because the fct(*operand) doesn't work for add and mul.

import operator

def mapexpression (expr, fctleaf, fctfct, param, level, addDepth=0, mulDepth=0) :
 def mapex (expr, depth) :               # a very local function
opor = expr.operator() opands = expr.operands() if (opor == None) :
     return fctleaf(expr,param) # a leaf in the expression tree
   if (opor == operator.add) :           # recursive call thru sum
     opands = map (lambda ex : mapex (ex, depth+addDepth), opands)
     return add (opands)
   if (opor == operator.mul) :           # recursive call thru mul
     opands = map (lambda ex : mapex (ex, depth+mulDepth), opands)
return mul (opands) if (level == -1) or (level[-1] >= depth) : # recursive call over operands
     opands = map (lambda ex : mapex (ex, depth+1), opands)
if level == -1 or depth in level : # root of the subtree must be changed
     return fctfct (opor, opands, param)
return opor (*opands) # opands may or maynot be changed by a recursive call
 return mapex (expr, 0)

def nn (ex, p) :
  if ex._is_numeric() or ex==pi: return ex.n(prec=p)
else : return ex
sage: mapexpression (sin(5*pi/7)+exp(i*pi/13),nn, lambda x,y,z:x(*y),20,-1)
1.7528 + 0.23932*I

Method __.n() doesn't work over partial numerical formula, but this mapexpression allows this.

Francois

--
To post to this group, send email to sage-support@googlegroups.com
To unsubscribe from this group, send email to 
sage-support+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/sage-support
URL: http://www.sagemath.org

Reply via email to