# Find length of intersection between 2 points and a sphere

I have a sphere and 2 points. The points have (x,y,z) coordinates and the sphere is defined by its centre (0,0,0) and radius R. I am trying to find the length between the 2 points which intersects the sphere. How can I script this out in Mathematica?

See below, my objective is length L:

• Find the distance from center of sphere to the line. Use that distance in the Pythagorean formula to get $L/2$. Jan 25, 2017 at 7:34
• "would it be possible to have the length of the line in the form of an equation?" - if you try following Louis's suggestion, you can get one. Look here to get the explicit formula for the distance from a point to a line. Jan 25, 2017 at 9:12

You can use RegionIntersection and RegionMeasure. Using the examples from the other answers:

RegionIntersection[Ball[{0,1,0}, 2], InfiniteLine[{{0,0,0},{2,1,1}}]]
RegionMeasure@%
%//N

(* Line[{{1/3 (1-Sqrt[19]),1/6 (1-Sqrt[19]),1/6 \
(1-Sqrt[19])},{1/3 (1+Sqrt[19]),1/6 (1+Sqrt[19]),1/6 \
(1+Sqrt[19])}}] *)

(* Sqrt[38/3] *)

(* 3.55903 *)

SeedRandom[0]
RegionIntersection[Ball[{0,0,0}, 3], InfiniteLine@@RandomReal[{-9, 9}, {2, 3}]]
RegionMeasure@%

(* Line[{{2.11448,-1.73651,-1.23025},{2.49353,0.749673,1.4900\
7}}] *)

(* 3.70471 *)


Lets say, you have a sphere centered at x0,y0,z0 with radius a and a line passing through x1,y1,z1 and x2,y2,z2. Then you can use Solve

{x0, y0, z0} = {0, 1, 0}
r = 2
{x1, y1, z1} = {0, 0, 0}
{x2, y2, z2} = {2, 1, 1}

intsct = {x, y, z} /. Solve[{x, y, z} ∈ InfiniteLine[{{x1, y1, z1}, {x2, y2, z2}}]
&& {x, y, z} ∈ Sphere[{x0, y0, z0}, r], {x, y, z}]


$\{\{\frac{1}{3}\text{ (1-}\sqrt{19}\text{),}\frac{1}{6}\text{ (1-}\sqrt{19}\text{),}\frac{1}{6}\text{ (1-}\sqrt{19}\text{)$\}$,$\{$}\frac{1}{3}\text{ (1+}\sqrt{19}\text{),}\frac{1}{6}\text{ (1+}\sqrt{19}\text{),}\frac{1}{6}\text{ (1+}\sqrt{19}\text{)$\}\}$}$

EuclideanDistance[intsct[[1]], intsct[[2]]]//N


3.55903

Graphics3D[{InfiniteLine[{{x1, y1, z1}, {x2, y2, z2}}],
PointSize[Large], Point[intsct], Opacity[0.5], Sphere[{x0, y0, z0}, r]}]


• could i set {x0, y0, z0} = {0, 0, 0}? Jan 25, 2017 at 8:27
• also, would it be possible to have the length of the line in the form of an equation? Jan 25, 2017 at 8:28
• What do you think ;) ? For the second question, if you know the equation of the sphere and line, it is possible. You can use Solve to get that. Jan 25, 2017 at 9:17

Let

R = 2;
c = {0, 1, 0};
{p1, p2} = {{0, 0, 0}, {2, 1, 1}}


and

line = InfiniteLine[p1, p2];
sphere = Sphere[c, R];

pts = RegionIntersection[sphere, line]


Graphics3D[{Opacity[0.5], sphere, line, Darker@Red, PointSize[Large], pts}, Axes -> True]


Then

d = RegionDistance[line, c]


$\sqrt{\frac{5}{6}}$

and

2 Sqrt[R^2 - d^2]


$\sqrt{\frac{38}{3}}$

N@%


3.55903

or

EuclideanDistance @@ Catenate[List @@ pts] // FullSimplify


$\sqrt{\frac{38}{3}}$

• would it be possible to have the length of the line in the form of an equation? Jan 25, 2017 at 8:28