# Extend a function to all polynomials ( just 2 variables) when one knows its values on monomials

I need your help to make my code faster.

I have a formula for computing a value from any monomial $x^i y^j$, say formular1[i_,j_]:=(Gamma[i]/Gamm[j] ). It is just an example, anyway.

My task is to extend this function to all polynomials f[x,y], as fast as possible.

One approach is to use CoefficientList to get a matrix of the coefficients of f[x,y]. Next, using Table[Table[...]...] to construct a matrix whose entries is the values of formular1[i,j]; Then multiply (entry by entry, not matrix multiplication) these 2 matrices and find the total of its entries.

This approach is slow when my polynomial is of high degree but sparse.

I once tried another approach:

Define

MonomialValue[c_ x^(i_) y^(j_)]:= c * formular1[i,j]
MonomialValue[x^(i_) y^(j_)]:= 1 * formular1[i,j]
MonomialValue[c_ x^(i_)]:= c * formular1[i,0]
MonomialValue[x^(i_)]:= 1 * formular1[i,0]
....
....


Then

PolynomialValue[f] :=  Total[MonomialValue /@ MonomialList[ f]]


This will avoid the unnecessary computing of formula[i,j] when the coefficient of f[x,y] is zero, also avoid the unnecessary entries in a huge matrix of coefficient.

The only disadvantage of this second approach is that I have to define MonomialValue for all kind of them. I can't not just define MonomialValue[c_ x^(i_) y^(j_)]. If I did so, then MonomialValue[x^2 y^3] (with coefficient 1) would not be evaluated. In order to make this works for all , I have to defined a total of 16 function.

I need this for just polynomials of 2 variables. But a generalization to several variables is appreciated.

Update

As noted by @user565739, my earlier solution does not work when i or j are unity (because the internal representation of z^1 does not involve Power). A simple generalization is as follows.

f = x^3 y^4 + x^7 y^2;
f /. {z1_^i_ z2_^j_ -> formular1[i, j], z1_ z2_^j_ -> formular1[1, j],
z1_^i_ z2_ -> formular1[i, 1], z1_ z2_ -> formular1[1, 1]}


with answer 2161/3. Likewise, for f = x^3 y + x y^2 the answer is 3/2.

• Thank you very much. How can I foget "Replace" and "ReplaceAll"...I used these 2 or 3 times before.... – user565739 Dec 12 '14 at 14:30
• This doesn't work when f is x^3 y, x^3 y^1, x^3 ...etc. This is the same problem as the second approach in my question. – user565739 Dec 14 '14 at 11:40
• @user565739, I have added special cases to accommodate either variable appearing linearly. Other special cases, like x^3 also can be added, although your particular choice of formular1 is singular for terms independent of y. – bbgodfrey Dec 14 '14 at 16:31
• Although what I really want is a solution that don't need to deal with all the exceptional situations, but you way is still better than my second approach that I mentioned. So I accepted your answer. Thank you. – user565739 Dec 16 '14 at 18:53