Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. a(a-b) = 0.5(a^2 - b^2 + (a-b)^2)
  2. a(a+b) = 0.5(a^2 + b^2 + (a-b)^2)
  3. a(3a-4b+2c) = 0.5(a^2 - b^2 + (2a-b)^2 - (2b-c)^2 + (a-2b+c)^2)
  4.  
  5. (3a - 4b + c)(9a - 24b + 22c - 8d + e)
  6.  
  7. polynomialToSquares[poly_, vars_] := Module[
  8. {basis = Plus[##]^2 & @@@ Tuples[vars, {2}] // Union, params}
  9. , params = Block[{x}, Array[Unique[x] &, Length@basis]]
  10. ; basis.params /. First@SolveAlways[poly == basis.params, vars]
  11. ]
  12. polynomialToSquares[poly_] := polynomialToSquares[poly, Variables@poly]
  13.  
  14. poly = a (a + b);
  15. polynomialToSquares[poly]
  16. poly - % // Expand
  17. (* (3 a^2)/2 + b^2/2 - 1/2 (a + b)^2 *)
  18. (* 0 *)
  19.  
  20. poly = a (3 a - 4 b + 2 c);
  21. polynomialToSquares[poly]
  22. poly - % // Expand
  23. (* 4 a^2 + 2 b^2 - 2 (a + b)^2 - c^2 + (a + c)^2 *)
  24. (* 0 *)
  25.  
  26. SeedRandom[10];
  27. poly = Union[Times @@@ Tuples[vars, {2}]].RandomInteger[{-20, 20}, 10]
  28. polynomialToSquares[poly]
  29. poly - % // Expand
  30. (* 3 a^2 + 15 a b + 18 b^2 + 2 a c + 12 b c + c^2 + 10 a d - 9 b d + 20 c d - 13 d^2 *)
  31. (* -((21 a^2)/2) + 9 b^2 + 15/2 (a + b)^2 - 16 c^2 + (a + c)^2 + 6 (b + c)^2 - (47 d^2)/2 + 5 (a + d)^2 - 9/2 (b + d)^2 + 10 (c + d)^2 *)
  32. (* 0 *)
  33.  
  34. ClearAll@polynomialToSquares
  35. polynomialToSquares[poly_, vars_] := Module[{
  36. monomialBasis = Times @@@ Tuples[vars, {2}] // Union
  37. , squaredBasis = Plus[##]^2 & @@@ Tuples[vars, {2}] // Union
  38. , tempVars = Block[{x}, Array[Unique[x] &, 2 Length@vars]]
  39. , basisTransformation
  40. }
  41. , basisTransformation = Normal@Last@CoefficientArrays[
  42. Expand@squaredBasis /. Thread[monomialBasis -> tempVars], tempVars
  43. ]
  44. ; Last@CoefficientArrays[poly /. Thread[monomialBasis -> tempVars], tempVars].Inverse[basisTransformation].squaredBasis
  45. ]
  46. polynomialToSquares[poly_] := polynomialToSquares[poly, Variables@poly]
  47.  
  48. basis = {a^2, b^2, (a + b)^2};
  49.  
  50. First@SolveAlways[a (a - b) == Array[$x, 3].basis, {a, b}]
  51. (* {$x[1] -> 3/2, $x[3] -> -(1/2), $x[2] -> 1/2} *)
  52.  
  53. Array[$x, 3].basis - a (a - b) /. {$x[1] -> 3/2, $x[3] -> -(1/2), $x[2] -> 1/2} // Expand
  54. (* 0 *)
  55.  
  56. basis = {a^2, b^2, c^2, (a + b)^2, (a + c)^2, (b + c)^2};
  57.  
  58. RandomSeed[10];
  59. poly = RandomInteger[{-10, 10}, 9].(Times @@@ Tuples[{a, b, c}, {2}])
  60. (* -2 a^2 - 2 a b - 7 b^2 - 2 a c - 16 b c - 3 c^2 *)
  61.  
  62. soln = First@SolveAlways[poly == Array[$x, 6].basis, {a, b, c}];
  63. Array[$x, 6].basis - poly /. soln // Expand
  64. (* 0 *)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement