Functions to calculate the visible width / height at a given z-depth from a perspective camera

Here’s the binary search that (theoretically) finds the depth at which sizing matches pixels of the viewport:

function findScreenDepth( camera, renderer ) {
    const { near, far } = camera
    const { height:physicalViewHeight } = renderer.getDrawingBufferSize()
    console.log( window.innerHeight, physicalViewHeight )
    const threshold = 0.000001

    return _findScreenDepth( near, far )

    function _findScreenDepth( near, far ) {

        const midpoint = ( far - near ) / 2 + near
        const midpointHeight = visibleHeightAtZDepth( -midpoint, camera )

        if ( Math.abs( ( physicalViewHeight / midpointHeight ) - 1 ) <= threshold )
            return midpoint

        if ( physicalViewHeight < midpointHeight )
            return _findScreenDepth( near, midpoint )
        else if ( physicalViewHeight > midpointHeight )
            return _findScreenDepth( midpoint, far )
        else if ( midpointHeight == physicalViewHeight ) // almost never happens
            return midpoint
    }
}

But the results are not as accurate as I hoped. In the following codepen, you see the depth is logged to console.

(Open the demo on desktop, make sure the viewable area has bigger height than in the following embed, or else the red line does not show)

If you set the height value of the red box to match the height value of the window, you’ll notice the red box is slightly taller than the viewport, and you have to give it a size that is slightly smaller than the window for it to fit just right.

Maybe this is because of floating point error?

What would be the correct way to get this depth, if not with this binary search?