The idea: calibration with a ruler
The browser doesn't know the physical size of the screen. With the ruler you give it that information: when the virtual marks fall on the real ones, we know how many CSS pixels cover 1 real centimetre. That figure, call it p (px/cm), is the whole basis of the calculation.
The DPI formula
One inch = 2.54 cm, and each CSS pixel maps to DPR physical pixels of the panel. So the physical pixels per inch (the DPI) are:
$$\mathrm{DPI} = p \times 2.54 \times \mathrm{DPR}$$
We measure it separately for the horizontal and the vertical ruler and show the average:
$$\mathrm{DPI} = \frac{\mathrm{DPI}_H + \mathrm{DPI}_V}{2}$$
In your measurement: p ≈ — px/cm · DPR — → DPI ≈ — ppi
Physical size and diagonal
Knowing how many CSS pixels = 1 inch (that is p × 2.54, the «CSS ppi»), the physical width comes from dividing the screen resolution (in CSS pixels) by it. Likewise the height:
$$w = \frac{W_{\mathrm{px}}}{p_H \times 2.54}, \qquad h = \frac{H_{\mathrm{px}}}{p_V \times 2.54}$$
And the diagonal from the Pythagorean theorem:
$$D = \sqrt{\,w^{2} + h^{2}\,}$$
In your measurement: w ≈ —″ · h ≈ —″ · D ≈ —″
Why the DPR is needed
On high-density (retina) screens a CSS pixel is not one physical pixel; it is DPR physical ones (e.g. 2×2 = 4). The ruler measures in CSS pixels, so to reach the real pixels of the panel we multiply by the DPR. Without it, the DPI would come out half (the «CSS ppi»).