# How to expand a function as a linear combination of other functions?

I would like to be able to expand certain functions as linear combinations of other specified functions when I know that the original function can be represented in such a way e.g. we know that $$\sin^{2}(x)$$ can be represented as a finite linear combination of $$1$$ and $$\cos(2x)$$, so I want to be able to tell Mathematica to find the coefficients in the linear combination (which here would be $$1/2$$ and $$- 1/2$$, respectively).

Is there a command or a simple piece of code which will do this:

1. without being specific to Fourier series, so can be applied to combinations of other (pre-specified) functions more generally, and
2. doesn't rely on numerical evaluation of the functions anywhere?

Thanks in advance for any help.

• The whole problem simplifies, if the specified set of functions--basis--is orthonormal. In this case the expansion coefficients can be computed by projection. In application to functional basis, the projection would be integration. Oct 17, 2021 at 21:16

Normally I'd use SolveAlways, but unfortunately that will not always work. For instance:

SolveAlways[u*Cos[x]^2 + v*Sin[x]^2 == 1, x]
(* {{}, {u -> v + Sec[x]^2 - v Sec[x]^2}, {v -> 1}} *)


_

Another way is to do a minimization of the total square difference (or could be Abs difference) between your linear combo and the target function. This actually works here, entirely symbolically:

Values@Last@Minimize[
Integrate[({u, v} . {1, Cos[2 x]} - Sin[x]^2)^2, {x, 0, 2 Pi}], {u, v}]

(* {1/2, -(1/2)} *)


Alternatively, there is Orthogonalize. First you need to choose an interval you want it to be linear on. It could be $$[0,2\pi]$$ or $$(-\infty,\infty)$$ for example. You then define an inner product which must converge on your interval. Use Orthogonalize to produce a new orthogonal basis which is properly normalized.

a = 0;
b = 2 Pi;
innerproduct[u_, v_] := Integrate[u v, {x, a, b}]
unnormedbasis = {1, Cos[2 x]};
basis = Orthogonalize[unnormedbasis, innerproduct];
consts = basis/unnormedbasis;
projection = innerproduct[Sin[x]^2, #] & /@ basis
Sin[x]^2 == projection . basis
FullSimplify[(projection*consts) . unnormedbasis == Sin[x]^2]
(* True *)

projection*consts
(* {1/2, -(1/2)} *)


In cases where you don't have an exact linear combination, you can use this technique to work out approximations. For instance, this finds an approximation to $\sqrt{x}$ in terms of a linear combination of some basis polynomials:

a = 0;
b = 1;
innerproduct[u_, v_] := Integrate[u v, {x, a, b}]
unnormedbasis = {1, x, x^2, x^3};
basis = Orthogonalize[unnormedbasis, innerproduct];
consts = basis/unnormedbasis;
projection = innerproduct[Sqrt[x], #] & /@ basis

Simplify[basis]
result = FullSimplify[projection . basis]
(* 8/63 (1 + x (15 + x (-15 + 7 x))) *)

Plot[{Sqrt[x], result}, {x, a, b}]