Math formula for transforming from EPSG:4326 to EPSG:3857
Projection EPSG:3857
uses the method EPSG:1024
for Forward and Reverse calculations.
The method is fully documented at Geomatics Guidance Note No 7, part 2
There's an mathematical example at page 40 where you can use to cross-reference your code.
17/11/2020 EDIT: The link to the above documentation from times to times, gets broken as things evolve. If that happens please feel free to update it as necessary.