1
$\begingroup$

What is the Mathematica equivalent(s) of the Wolfram Alpha command to get the center and radius of a sphere given by an expression, e.g. (in Wolfram Alpha);

x^2+y^2+z^2+8x-6y-4z-7=0 calculate center and radius

which returns 6 and $(-4,3,2)$.

$\endgroup$
1
$\begingroup$

It turns out if you just minimize the lhs of the equation, you get $-r^2$ and the centers immediately, and $r=\sqrt{|-36|}=6$:

Minimize[x^2 + y^2 + z^2 + 8 x - 6 y - 4 z - 7, {x, y, z}]
(* result: {-36, {x -> -4, y -> 3, z -> 2}} *)

Why does this work? The value of $s(x,y,z)=(x-x_0)^2+(y-y_0)^2+(z-z_0)^2-r^2$ is precisely $0$ on the sphere surface, positive on the exterior of the sphere, and negative on the interior. It's easy to see that $s(x_0,y_0,z_0)=-r^2$ and the gradient $\nabla s(x,y,z)=2 (x - x_0)\mathbf{i}+ 2 (y - y_0)\mathbf{j}+ 2 (z - z_0)\mathbf{k}$ is zero at the center and grows outwards in all directions.


Note: I didn't consider this as your equation has no leading coefficients of $x^2,y^2,z^2$ which means the above solution works. However, @yarchik pointed out a problem if the sphere equation is scaled and starts with $k x^2+ky^2+kz^2+...$ where $k\neq1$ then Minimize will produce the correct centers but gives a minimum value of $-kr^2$. So you will need to take this into account, for example here's the same sphere from a proportional equation:

s = Expand[(x^2 + y^2 + z^2 + 8 x - 6 y - 4 z - 7)/100];
m = Minimize[s, {x, y, z}]; (* returns {-(9/25), {x -> -4, y -> 3, z -> 2}} *)
centers = {x, y, z} /. Last[m]; (* {-4, 3, 2} *)
radius = Sqrt[Abs[First[m]/Coefficient[s, x^2]]]; (* 6 *)

Alternatively, if you can find 4 points on the sphere surface (using FindInstance) then that's all you need to get the centers and the radius:

eq = x^2 + y^2 + z^2 + 8 x - 6 y - 4 z - 7;
sphere = (x - c1)^2 + (y - c2)^2 + (z - c3)^2 - r^2;
points = {x, y, z} /. FindInstance[eq == 0, {x, y, z}, Reals, 4];
system = ((sphere - eq) == 0 && r > 0 /. {x -> #[[1]], y -> #[[2]], z -> #[[3]]}) & /@ points;
Solve[system, {c1, c2, c3, r}]
$\endgroup$
2
  • $\begingroup$ Your first solution is not correct. The same result should hold for a rescaled equation. But Minimize[(x^2 + y^2 + z^2 + 8 x - 6 y - 4 z - 7)/100, {x, y, z}] yields 3/5 as a radius. $\endgroup$
    – yarchik
    Jun 22 '20 at 11:54
  • $\begingroup$ @yarchik you are right - the centers are correct though and the radius easily follows from that - I will correct the answer. This is only relevant if the x^2, y^2,z^2 have leading coefficients $\endgroup$
    – flinty
    Jun 22 '20 at 11:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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