The formulas to calculate the position of Mars and Earth are documented in Meeus' book. The book's formulas are truncated from the original formulas for conciseness.

The formula system is called "VSOP87". It's one crucial property is that you can choose the accuracy of the result by using different numbers of terms. In addition, you can calculate the accuracy explicitly using the values in the system.

The systems are available to calculate XYZ of the planets as well as spherical coordinates. Once the earth's xyz and mars' xyz are known, it's simple trig to get the distance from a given longitude, latitude and altitude.