Trig Expression Combinatorics
Programing Challange. All Possible Expression Combination
In python or your favorite programing language, write a function
expr_generator(funcList, n)
- funcList is a list of function names, such as sine, cosine, inverse, power, plus, times, etc.
- n is a integer, means max of n level of nesting of function in result. e.g.
expr_generator(["sin"], 3)
result should containlambda x: math.sin(math.sin(math.sin(x)))
.
- Return a list of all possible combination of funcList.
- Each element in result is a callable function
f(x,y)
that takes 2 args and return a number. - The
expr_generator
must be able to cover all possible combinations, including nested expression e.g.sin(sin(x))
import math print((lambda x: math.sin(math.sin(math.sin(x))))(1))
Mathematica Code
The following is Mathematica code that generates all possible equations of one term. (tweak the funList and nesting level to define what “all possible” means. if nesting level is 2, it takes about 20 minutes and returns a list of some 2876 terms on a 2002 personal computer.
<< DiscreteMath`Combinatorica` funList = {Sin, Tan, Power[#, -1] &}; Nest[Module[{li = #}, (Union[#, SameTest -> (Module[{arg1 = #1, arg2 = #2}, If[(*both expression contains both x and y*) And @@ (((((StringMatchQ[#, "*x*"] && StringMatchQ[#, "*y*"]) &)@ ToString@#) &) /@ {arg1, arg2}) , SameQ[arg1, arg2 /. {x -> y, y -> x}], SameQ[arg1, arg2]] ] &)] &)@ Union@Flatten@(Table[(Times @@ # &) /@ KSubsets[#, i], {i, 1, 2}] &)@Flatten@{li, Outer[#1@#2 &, funList, li]} ] &, {x, y}, 1]; Select[%, (StringMatchQ[ToString@#, "*x*"] && StringMatchQ[ToString@#, "*y*"]) &]
Here are the first few items of the result, with nesting level at 2:
{1/(x^2*y^2), 1/(x*y^2), x/y^2, 1/(x*y), x/y, x^2/y, x*y, x^2*y, x^2*y^2, Cos[x]/y^2, Cos[x]/y, Cos[x]/(x*y), (x*Cos[x])/y, y*Cos[x], (y*Cos[x])/x, x*y*Cos[x], y^2*Cos[x], Cos[x]*Cos[y], Cot[x]/y^2, Cot[x]/(x*y^2)}
The problem is to enumerate all possible single-term expressions of 2 variables x and y, using all the trig functions, multiplication and its inverse, integer power and its inverse (roots), and nesting.