Question: 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:

[![enter image description here](https://i.stack.imgur.com/Vp4GS.png)](https://i.stack.imgur.com/Vp4GS.png)

Answer: 
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]}]

```

[![enter image description here](https://i.stack.imgur.com/34544.png)](https://i.stack.imgur.com/34544.png)
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]

```

[![enter image description here](https://i.stack.imgur.com/Bto2Y.png)](https://i.stack.imgur.com/Bto2Y.png)

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

```

[![enter image description here](https://i.stack.imgur.com/aShhu.png)](https://i.stack.imgur.com/aShhu.png)

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}}$
> 
> 
>