Re: simplify math expression
- Posted by David Cuny <dcuny at LANSET.COM> Jun 11, 2002
- 477 views
tone skoda wrote: > b+(c+(a+d)) --> a+b+c+d > c+((d+b)+a) --> a+b+c+d > (b*a)/c --> a*b/c > a/(b/c) --> a*c/b > b*(c+a) --> a*b+a*c This looks a lot like a Prolog sort of problem. Assuming you represented the data in a sequence, such as: a --> 'a' a+b --> {'a', '+', 'b'} b+(c+(a+d)) --> { 'b', '+', { 'c', '+', { 'a', '+', 'd' } } } you should be able to write a 'simplify' routine to do the work for you. Something like this: function simp( object o ) object a, b, tmp atom op sequence s -- a --> a if atom( o ) then return o else a = simp(o[1]) op = o[2] b = simp(o[3]) -- b + a --> a + b -- b * a --> a * b if atom(a) and (op = '+' or op = '*') and atom(b) and a > b then return { b, op, a } -- ( (...) + a ) --> (a + (...) ) -- ( (...) * a ) --> (a * (...) ) elsif sequence(a) and (op = '+' or op = '*') and atom(b) then return simp( { b, op, a } ) -- ( a + ( b + c ) ) --> (a + ( b + c ) ) -- ( a * ( b * c ) ) --> (a * ( b * c ) ) elsif atom(a) and (op = '+' or op = '*') and sequence(b) and atom(b[1]) and b[2] = op and atom(b[3]) then s = sort( { a, b[1], b[3] } ) return { s[1], op, { s[2], op, s[3] } } -- a * ( b op c ) --> ( a * b ) op ( a * c ) elsif atom(a) and op = '*' and sequence(b) then tmp = { { a, '*', b[1] }, b[2], { a, '*', b[3] } } return simp( tmp ) else return { a, op, b } end if end function This is entirely untested (and incomplete), but captures the general idea. -- David Cuny