Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I transform a quadratic polynomial in x and y into an equation of the form $(x-a)^2+(y-b)^2=c$?

f = -9 x + (3 x^2)/4 + (3 y^2)/4;

Completing the Square

CompleteSquare[f_, x_] :=
  Module[{a, b, c},
    {c, b, a} = CoefficientList[f, x];  
    a (x + b/2/a)^2 + Simplify[(c - b^2/4/a)]]

CompleteSquare[f, x]

(*
    3/4 (-6 + x)^2 + 3/4 (-36 + y^2)
*)

What I want is the following:

(x - 6)^2 + y^2 == 36
share|improve this question
coeffs[expr_, vars_]:= Flatten[CoefficientList[expr, vars]]

CompleteSquare[expr_, {x_, y_}]:= Module[{a, b, c, c1, c2, eqns, sols}, 
    eqns = Thread[coeffs[c1 (x - a)^2 + c2 (y - b)^2 - c, {x, y}] - coeffs[f, {x, y}] == 0];
    Check[sols = Solve[eqns, {a, b, c, c1, c2}], Return@$Failed];
    (x - a)^2 + c2/c1 (y - b)^2 == c/c1 /. sols
]

Now for the specific example.

f = -9 x + (3 x^2)/4 + (3 y^2)/4;
CompleteSquare[f, {x, y}]

(*{(-6 + x)^2 + y^2 == 36}*)
share|improve this answer

Let first make the CompleteSquare[f_, x_] function according to your reference.

(* Destination Function = X1(x) = A*(x-B)^2, X2 = C  such that X1+X2 = f *)

CompleteSquare[f_, x_] := Module[{a, b, c}, 
{c, b, a} = Table[Coefficient[f, x, i], {i, 0, 2}]; X1 = a (x + b/(2 a))^2;
X2 = (c - b^2/(4 a)); Print[X1, "+" X2]]

When you run CompleteSquare[f, x] it will create X1 and X2 which will have the perfect square and additive part and Print their sum. For your example

f = -9 x + (3 x^2)/4 + (3 y^2)/4;

CompleteSquare[f, x]
X1
X2

And your desired equation is X1 + X2 == 0.

share|improve this answer
    
You really shouldn't define functions in a way that they modify external variables!! – sebhofer Jul 12 '13 at 14:46

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.