First, it simplifies the process to convert the ray to the sphere's object space, which means that the sphere will be centered at (0,0,0). So, a point P will lie on the surface of the sphere of radius R if the P*P = R*R. We can substitue our ray with an origin point O and direction vector D for the point P, and then find the distance t at which our ray intersects the sphere by setting (O + tD)*(O + tD) = R*R. Expanding this gives us a quadratic equation which can then be solved using the Quadratic formula, with the following values for our A, B, and C variables and the two possible solutions t0 and t1 to our equation:
(D*D)t^2 + 2(D*O)t + O*O - R*R = 0
A = D*D
B = 2(O*D)
C = O*O - R*R
t0 = (-B - sqrt(B^2 - 4AC)) / 2A
t1 = (-B + sqrt(B^2 - 4AC)) / 2A
Depending on the values of A, B, and C, the solutions might be imaginary numbers. If this is the case, then it means that the ray does not intersect the sphere. We can easily determine if the solution will be imaginary based on whether or not the discriminant, B^2 - 4AC, is less than zero. If it is, then we simply stop right there and move on to the next ray. If the discriminant is positive then calculate the two solutions and store them in variables. In order to cut down on precision errors, t0 and t1 can be calculated as:
t0 = q / A
t1 = C / q
where q = (-B + sqrt(B^2 - 4AC)) if B < 0
and q = (-B - sqrt(B^2 - 4AC)) otherwise
If t1 is smaller than t0, we swap the values. Now we check to see if t1 is less than zero. If it is we know that it's intersection is behind the camera, and since we know that t1 is larger than t0, we can conclude that t0 is also behind the camera. Since both intersections are behind the camera, we return false. If t1 is positive, then we check to see if t0 is negative. If t0 is not negative, then we pass it back and return true. Otherwise, we pass back t1 and return true.
Remember that Ray r has been converted to object space, so the sphere is centered at the origin. Also, rad holds the radius of the sphere and t is used to pass back the closest intersection.