Reputation: 747
I need an algorithm to compute higher order polynomial from 3 random variables e.g. X,Y,Z
I need the up to degree 9 of polynomials. for example:
Degree 2:
X * Y
X * Z
Y * Z
Degree 3:
X * Y * Z
X^2 * Y
X^2 * Z
Y^2 * X
Y^2 * Z
Z^2 * X
Z^2 * Y
.
.
.
Degree 9:
X^3*Y^3*Z^3
.
.
.
I believe three inner "for loop" will solve this but I can't figure it out. Any help is appreciated. Thanks
Upvotes: 1
Views: 827
Reputation: 16987
In Python for example I would do something like this:
from itertools import permutations
for p in permutations([0,1,2,3] * 3, 3):
if sum(p) >= 2:
print("x^{} * y^{} * z^{}".format(*p))
Basically, loop through all length 3 permutations of coefficients [0,1,2,3] * 3
(0 to 3 repeated 3 times).
Here is a link to Heap's algorithm for generating the permutations along with some pseudo code:
https://en.m.wikipedia.org/wiki/Heap%27s_algorithm
Upvotes: 0
Reputation: 520908
Here is a brute force Java solution. You simply can iterate over all exponent values from through 9 inclusive and retain those configurations where the overall order be less than or equal to 9.
for (int i=0; i <= 9; ++i) {
for (int j=0; j <= 9; ++j) {
for (int k=0; k <= 9; ++k) {
if (i + j + k >= 2 && i + j + k <= 9) {
System.out.println("x^" + i + "*y^" + j + "*z^" + k);
}
}
}
}
You can port this over to R fairly easily, but as loops tend to be frowned upon in R, there is probably a more proper (and possibly faster) way to do it.
Upvotes: 2