← Back to archive
Data Forecasting

Handling Floating-Point Precision Problems

历法

When converting to a JD value during calculation — for example, for 00:00:00 on January 1, 2000, the JD value is 2451545.4166707597 — restoration yields December 31, 1999, 23:59:59.999986588954926, due to floating-point arithmetic issues.

After a manual correction adding one second (1/86400), the seconds become 0.999981164932251111; in other words, the stable floating-point value here is around 0.99998. Since 1000 milliseconds make one second and astronomical calculations cannot be that precise anyway, the computation can be simplified.

Therefore, a floating-point correction is needed:

var xxx = Math.Round(v - Math.Floor(v), 6);
if (xxx < 0.50001)
{
 jd = v - xxx - 0.5 + 0.00001;
}
if (xxx > 0.50001)
{
 jd = Math.Floor(v) + 0.50001;
}

return jd;

Written by Master Sanfu on July 25, 2016. Please credit the source if you share.

Translation Notice: This English version was translated with AI assistance. Specialized, historical, religious, or culturally sensitive terms may contain nuances, inaccuracies, or debatable wording. In case of ambiguity or discrepancy, the original Chinese text shall prevail.