CalendricalCalculationsHelper.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Diagnostics;
  5. namespace System.Globalization
  6. {
  7. internal class CalendricalCalculationsHelper
  8. {
  9. private const double FullCircleOfArc = 360.0; // 360.0;
  10. private const int HalfCircleOfArc = 180;
  11. private const double TwelveHours = 0.5; // half a day
  12. private const double Noon2000Jan01 = 730120.5;
  13. internal const double MeanTropicalYearInDays = 365.242189;
  14. private const double MeanSpeedOfSun = MeanTropicalYearInDays / FullCircleOfArc;
  15. private const double LongitudeSpring = 0.0;
  16. private const double TwoDegreesAfterSpring = 2.0;
  17. private const int SecondsPerDay = 24 * 60 * 60; // 24 hours * 60 minutes * 60 seconds
  18. private const int DaysInUniformLengthCentury = 36525;
  19. private const int SecondsPerMinute = 60;
  20. private const int MinutesPerDegree = 60;
  21. private static readonly long s_startOf1810 = GetNumberOfDays(new DateTime(1810, 1, 1));
  22. private static readonly long s_startOf1900Century = GetNumberOfDays(new DateTime(1900, 1, 1));
  23. private static readonly double[] s_coefficients1900to1987 = new double[] { -0.00002, 0.000297, 0.025184, -0.181133, 0.553040, -0.861938, 0.677066, -0.212591 };
  24. private static readonly double[] s_coefficients1800to1899 = new double[] { -0.000009, 0.003844, 0.083563, 0.865736, 4.867575, 15.845535, 31.332267, 38.291999, 28.316289, 11.636204, 2.043794 };
  25. private static readonly double[] s_coefficients1700to1799 = new double[] { 8.118780842, -0.005092142, 0.003336121, -0.0000266484 };
  26. private static readonly double[] s_coefficients1620to1699 = new double[] { 196.58333, -4.0675, 0.0219167 };
  27. private static readonly double[] s_lambdaCoefficients = new double[] { 280.46645, 36000.76983, 0.0003032 };
  28. private static readonly double[] s_anomalyCoefficients = new double[] { 357.52910, 35999.05030, -0.0001559, -0.00000048 };
  29. private static readonly double[] s_eccentricityCoefficients = new double[] { 0.016708617, -0.000042037, -0.0000001236 };
  30. private static readonly double[] s_coefficients = new double[] { Angle(23, 26, 21.448), Angle(0, 0, -46.8150), Angle(0, 0, -0.00059), Angle(0, 0, 0.001813) };
  31. private static readonly double[] s_coefficientsA = new double[] { 124.90, -1934.134, 0.002063 };
  32. private static readonly double[] s_coefficientsB = new double[] { 201.11, 72001.5377, 0.00057 };
  33. private static double RadiansFromDegrees(double degree)
  34. {
  35. return degree * Math.PI / 180;
  36. }
  37. private static double SinOfDegree(double degree)
  38. {
  39. return Math.Sin(RadiansFromDegrees(degree));
  40. }
  41. private static double CosOfDegree(double degree)
  42. {
  43. return Math.Cos(RadiansFromDegrees(degree));
  44. }
  45. private static double TanOfDegree(double degree)
  46. {
  47. return Math.Tan(RadiansFromDegrees(degree));
  48. }
  49. public static double Angle(int degrees, int minutes, double seconds)
  50. {
  51. return ((seconds / SecondsPerMinute + minutes) / MinutesPerDegree) + degrees;
  52. }
  53. private static double Obliquity(double julianCenturies)
  54. {
  55. return PolynomialSum(s_coefficients, julianCenturies);
  56. }
  57. internal static long GetNumberOfDays(DateTime date)
  58. {
  59. return date.Ticks / GregorianCalendar.TicksPerDay;
  60. }
  61. private static int GetGregorianYear(double numberOfDays)
  62. {
  63. return new DateTime(Math.Min((long)(Math.Floor(numberOfDays) * GregorianCalendar.TicksPerDay), DateTime.MaxValue.Ticks)).Year;
  64. }
  65. private enum CorrectionAlgorithm
  66. {
  67. Default,
  68. Year1988to2019,
  69. Year1900to1987,
  70. Year1800to1899,
  71. Year1700to1799,
  72. Year1620to1699
  73. }
  74. private struct EphemerisCorrectionAlgorithmMap
  75. {
  76. public EphemerisCorrectionAlgorithmMap(int year, CorrectionAlgorithm algorithm)
  77. {
  78. _lowestYear = year;
  79. _algorithm = algorithm;
  80. }
  81. internal int _lowestYear;
  82. internal CorrectionAlgorithm _algorithm;
  83. };
  84. private static readonly EphemerisCorrectionAlgorithmMap[] s_ephemerisCorrectionTable = new EphemerisCorrectionAlgorithmMap[]
  85. {
  86. // lowest year that starts algorithm, algorithm to use
  87. new EphemerisCorrectionAlgorithmMap(2020, CorrectionAlgorithm.Default),
  88. new EphemerisCorrectionAlgorithmMap(1988, CorrectionAlgorithm.Year1988to2019),
  89. new EphemerisCorrectionAlgorithmMap(1900, CorrectionAlgorithm.Year1900to1987),
  90. new EphemerisCorrectionAlgorithmMap(1800, CorrectionAlgorithm.Year1800to1899),
  91. new EphemerisCorrectionAlgorithmMap(1700, CorrectionAlgorithm.Year1700to1799),
  92. new EphemerisCorrectionAlgorithmMap(1620, CorrectionAlgorithm.Year1620to1699),
  93. new EphemerisCorrectionAlgorithmMap(int.MinValue, CorrectionAlgorithm.Default) // default must be last
  94. };
  95. private static double Reminder(double divisor, double dividend)
  96. {
  97. double whole = Math.Floor(divisor / dividend);
  98. return divisor - (dividend * whole);
  99. }
  100. private static double NormalizeLongitude(double longitude)
  101. {
  102. longitude = Reminder(longitude, FullCircleOfArc);
  103. if (longitude < 0)
  104. {
  105. longitude += FullCircleOfArc;
  106. }
  107. return longitude;
  108. }
  109. public static double AsDayFraction(double longitude)
  110. {
  111. return longitude / FullCircleOfArc;
  112. }
  113. private static double PolynomialSum(double[] coefficients, double indeterminate)
  114. {
  115. double sum = coefficients[0];
  116. double indeterminateRaised = 1;
  117. for (int i = 1; i < coefficients.Length; i++)
  118. {
  119. indeterminateRaised *= indeterminate;
  120. sum += (coefficients[i] * indeterminateRaised);
  121. }
  122. return sum;
  123. }
  124. private static double CenturiesFrom1900(int gregorianYear)
  125. {
  126. long july1stOfYear = GetNumberOfDays(new DateTime(gregorianYear, 7, 1));
  127. return (double)(july1stOfYear - s_startOf1900Century) / DaysInUniformLengthCentury;
  128. }
  129. // the following formulas defines a polynomial function which gives us the amount that the earth is slowing down for specific year ranges
  130. private static double DefaultEphemerisCorrection(int gregorianYear)
  131. {
  132. Debug.Assert(gregorianYear < 1620 || 2020 <= gregorianYear);
  133. long january1stOfYear = GetNumberOfDays(new DateTime(gregorianYear, 1, 1));
  134. double daysSinceStartOf1810 = january1stOfYear - s_startOf1810;
  135. double x = TwelveHours + daysSinceStartOf1810;
  136. return ((Math.Pow(x, 2) / 41048480) - 15) / SecondsPerDay;
  137. }
  138. private static double EphemerisCorrection1988to2019(int gregorianYear)
  139. {
  140. Debug.Assert(1988 <= gregorianYear && gregorianYear <= 2019);
  141. return (double)(gregorianYear - 1933) / SecondsPerDay;
  142. }
  143. private static double EphemerisCorrection1900to1987(int gregorianYear)
  144. {
  145. Debug.Assert(1900 <= gregorianYear && gregorianYear <= 1987);
  146. double centuriesFrom1900 = CenturiesFrom1900(gregorianYear);
  147. return PolynomialSum(s_coefficients1900to1987, centuriesFrom1900);
  148. }
  149. private static double EphemerisCorrection1800to1899(int gregorianYear)
  150. {
  151. Debug.Assert(1800 <= gregorianYear && gregorianYear <= 1899);
  152. double centuriesFrom1900 = CenturiesFrom1900(gregorianYear);
  153. return PolynomialSum(s_coefficients1800to1899, centuriesFrom1900);
  154. }
  155. private static double EphemerisCorrection1700to1799(int gregorianYear)
  156. {
  157. Debug.Assert(1700 <= gregorianYear && gregorianYear <= 1799);
  158. double yearsSince1700 = gregorianYear - 1700;
  159. return PolynomialSum(s_coefficients1700to1799, yearsSince1700) / SecondsPerDay;
  160. }
  161. private static double EphemerisCorrection1620to1699(int gregorianYear)
  162. {
  163. Debug.Assert(1620 <= gregorianYear && gregorianYear <= 1699);
  164. double yearsSince1600 = gregorianYear - 1600;
  165. return PolynomialSum(s_coefficients1620to1699, yearsSince1600) / SecondsPerDay;
  166. }
  167. // ephemeris-correction: correction to account for the slowing down of the rotation of the earth
  168. private static double EphemerisCorrection(double time)
  169. {
  170. int year = GetGregorianYear(time);
  171. foreach (EphemerisCorrectionAlgorithmMap map in s_ephemerisCorrectionTable)
  172. {
  173. if (map._lowestYear <= year)
  174. {
  175. switch (map._algorithm)
  176. {
  177. case CorrectionAlgorithm.Default: return DefaultEphemerisCorrection(year);
  178. case CorrectionAlgorithm.Year1988to2019: return EphemerisCorrection1988to2019(year);
  179. case CorrectionAlgorithm.Year1900to1987: return EphemerisCorrection1900to1987(year);
  180. case CorrectionAlgorithm.Year1800to1899: return EphemerisCorrection1800to1899(year);
  181. case CorrectionAlgorithm.Year1700to1799: return EphemerisCorrection1700to1799(year);
  182. case CorrectionAlgorithm.Year1620to1699: return EphemerisCorrection1620to1699(year);
  183. }
  184. break; // break the loop and assert eventually
  185. }
  186. }
  187. Debug.Fail("Not expected to come here");
  188. return DefaultEphemerisCorrection(year);
  189. }
  190. public static double JulianCenturies(double moment)
  191. {
  192. double dynamicalMoment = moment + EphemerisCorrection(moment);
  193. return (dynamicalMoment - Noon2000Jan01) / DaysInUniformLengthCentury;
  194. }
  195. private static bool IsNegative(double value)
  196. {
  197. return Math.Sign(value) == -1;
  198. }
  199. private static double CopySign(double value, double sign)
  200. {
  201. return (IsNegative(value) == IsNegative(sign)) ? value : -value;
  202. }
  203. // equation-of-time; approximate the difference between apparent solar time and mean solar time
  204. // formal definition is EOT = GHA - GMHA
  205. // GHA is the Greenwich Hour Angle of the apparent (actual) Sun
  206. // GMHA is the Greenwich Mean Hour Angle of the mean (fictitious) Sun
  207. // http://www.esrl.noaa.gov/gmd/grad/solcalc/
  208. // http://en.wikipedia.org/wiki/Equation_of_time
  209. private static double EquationOfTime(double time)
  210. {
  211. double julianCenturies = JulianCenturies(time);
  212. double lambda = PolynomialSum(s_lambdaCoefficients, julianCenturies);
  213. double anomaly = PolynomialSum(s_anomalyCoefficients, julianCenturies);
  214. double eccentricity = PolynomialSum(s_eccentricityCoefficients, julianCenturies);
  215. double epsilon = Obliquity(julianCenturies);
  216. double tanHalfEpsilon = TanOfDegree(epsilon / 2);
  217. double y = tanHalfEpsilon * tanHalfEpsilon;
  218. double dividend = ((y * SinOfDegree(2 * lambda))
  219. - (2 * eccentricity * SinOfDegree(anomaly))
  220. + (4 * eccentricity * y * SinOfDegree(anomaly) * CosOfDegree(2 * lambda))
  221. - (0.5 * Math.Pow(y, 2) * SinOfDegree(4 * lambda))
  222. - (1.25 * Math.Pow(eccentricity, 2) * SinOfDegree(2 * anomaly)));
  223. double divisor = 2 * Math.PI;
  224. double equation = dividend / divisor;
  225. // approximation of equation of time is not valid for dates that are many millennia in the past or future
  226. // thus limited to a half day
  227. return CopySign(Math.Min(Math.Abs(equation), TwelveHours), equation);
  228. }
  229. private static double AsLocalTime(double apparentMidday, double longitude)
  230. {
  231. // slightly inaccurate since equation of time takes mean time not apparent time as its argument, but the difference is negligible
  232. double universalTime = apparentMidday - AsDayFraction(longitude);
  233. return apparentMidday - EquationOfTime(universalTime);
  234. }
  235. // midday
  236. public static double Midday(double date, double longitude)
  237. {
  238. return AsLocalTime(date + TwelveHours, longitude) - AsDayFraction(longitude);
  239. }
  240. private static double InitLongitude(double longitude)
  241. {
  242. return NormalizeLongitude(longitude + HalfCircleOfArc) - HalfCircleOfArc;
  243. }
  244. // midday-in-tehran
  245. public static double MiddayAtPersianObservationSite(double date)
  246. {
  247. return Midday(date, InitLongitude(52.5)); // 52.5 degrees east - longitude of UTC+3:30 which defines Iranian Standard Time
  248. }
  249. private static double PeriodicTerm(double julianCenturies, int x, double y, double z)
  250. {
  251. return x * SinOfDegree(y + z * julianCenturies);
  252. }
  253. private static double SumLongSequenceOfPeriodicTerms(double julianCenturies)
  254. {
  255. double sum = 0.0;
  256. sum += PeriodicTerm(julianCenturies, 403406, 270.54861, 0.9287892);
  257. sum += PeriodicTerm(julianCenturies, 195207, 340.19128, 35999.1376958);
  258. sum += PeriodicTerm(julianCenturies, 119433, 63.91854, 35999.4089666);
  259. sum += PeriodicTerm(julianCenturies, 112392, 331.2622, 35998.7287385);
  260. sum += PeriodicTerm(julianCenturies, 3891, 317.843, 71998.20261);
  261. sum += PeriodicTerm(julianCenturies, 2819, 86.631, 71998.4403);
  262. sum += PeriodicTerm(julianCenturies, 1721, 240.052, 36000.35726);
  263. sum += PeriodicTerm(julianCenturies, 660, 310.26, 71997.4812);
  264. sum += PeriodicTerm(julianCenturies, 350, 247.23, 32964.4678);
  265. sum += PeriodicTerm(julianCenturies, 334, 260.87, -19.441);
  266. sum += PeriodicTerm(julianCenturies, 314, 297.82, 445267.1117);
  267. sum += PeriodicTerm(julianCenturies, 268, 343.14, 45036.884);
  268. sum += PeriodicTerm(julianCenturies, 242, 166.79, 3.1008);
  269. sum += PeriodicTerm(julianCenturies, 234, 81.53, 22518.4434);
  270. sum += PeriodicTerm(julianCenturies, 158, 3.5, -19.9739);
  271. sum += PeriodicTerm(julianCenturies, 132, 132.75, 65928.9345);
  272. sum += PeriodicTerm(julianCenturies, 129, 182.95, 9038.0293);
  273. sum += PeriodicTerm(julianCenturies, 114, 162.03, 3034.7684);
  274. sum += PeriodicTerm(julianCenturies, 99, 29.8, 33718.148);
  275. sum += PeriodicTerm(julianCenturies, 93, 266.4, 3034.448);
  276. sum += PeriodicTerm(julianCenturies, 86, 249.2, -2280.773);
  277. sum += PeriodicTerm(julianCenturies, 78, 157.6, 29929.992);
  278. sum += PeriodicTerm(julianCenturies, 72, 257.8, 31556.493);
  279. sum += PeriodicTerm(julianCenturies, 68, 185.1, 149.588);
  280. sum += PeriodicTerm(julianCenturies, 64, 69.9, 9037.75);
  281. sum += PeriodicTerm(julianCenturies, 46, 8.0, 107997.405);
  282. sum += PeriodicTerm(julianCenturies, 38, 197.1, -4444.176);
  283. sum += PeriodicTerm(julianCenturies, 37, 250.4, 151.771);
  284. sum += PeriodicTerm(julianCenturies, 32, 65.3, 67555.316);
  285. sum += PeriodicTerm(julianCenturies, 29, 162.7, 31556.08);
  286. sum += PeriodicTerm(julianCenturies, 28, 341.5, -4561.54);
  287. sum += PeriodicTerm(julianCenturies, 27, 291.6, 107996.706);
  288. sum += PeriodicTerm(julianCenturies, 27, 98.5, 1221.655);
  289. sum += PeriodicTerm(julianCenturies, 25, 146.7, 62894.167);
  290. sum += PeriodicTerm(julianCenturies, 24, 110.0, 31437.369);
  291. sum += PeriodicTerm(julianCenturies, 21, 5.2, 14578.298);
  292. sum += PeriodicTerm(julianCenturies, 21, 342.6, -31931.757);
  293. sum += PeriodicTerm(julianCenturies, 20, 230.9, 34777.243);
  294. sum += PeriodicTerm(julianCenturies, 18, 256.1, 1221.999);
  295. sum += PeriodicTerm(julianCenturies, 17, 45.3, 62894.511);
  296. sum += PeriodicTerm(julianCenturies, 14, 242.9, -4442.039);
  297. sum += PeriodicTerm(julianCenturies, 13, 115.2, 107997.909);
  298. sum += PeriodicTerm(julianCenturies, 13, 151.8, 119.066);
  299. sum += PeriodicTerm(julianCenturies, 13, 285.3, 16859.071);
  300. sum += PeriodicTerm(julianCenturies, 12, 53.3, -4.578);
  301. sum += PeriodicTerm(julianCenturies, 10, 126.6, 26895.292);
  302. sum += PeriodicTerm(julianCenturies, 10, 205.7, -39.127);
  303. sum += PeriodicTerm(julianCenturies, 10, 85.9, 12297.536);
  304. sum += PeriodicTerm(julianCenturies, 10, 146.1, 90073.778);
  305. return sum;
  306. }
  307. private static double Aberration(double julianCenturies)
  308. {
  309. return (0.0000974 * CosOfDegree(177.63 + (35999.01848 * julianCenturies))) - 0.005575;
  310. }
  311. private static double Nutation(double julianCenturies)
  312. {
  313. double a = PolynomialSum(s_coefficientsA, julianCenturies);
  314. double b = PolynomialSum(s_coefficientsB, julianCenturies);
  315. return (-0.004778 * SinOfDegree(a)) - (0.0003667 * SinOfDegree(b));
  316. }
  317. public static double Compute(double time)
  318. {
  319. double julianCenturies = JulianCenturies(time);
  320. double lambda = 282.7771834
  321. + (36000.76953744 * julianCenturies)
  322. + (0.000005729577951308232 * SumLongSequenceOfPeriodicTerms(julianCenturies));
  323. double longitude = lambda + Aberration(julianCenturies) + Nutation(julianCenturies);
  324. return InitLongitude(longitude);
  325. }
  326. public static double AsSeason(double longitude)
  327. {
  328. return (longitude < 0) ? (longitude + FullCircleOfArc) : longitude;
  329. }
  330. private static double EstimatePrior(double longitude, double time)
  331. {
  332. double timeSunLastAtLongitude = time - (MeanSpeedOfSun * AsSeason(InitLongitude(Compute(time) - longitude)));
  333. double longitudeErrorDelta = InitLongitude(Compute(timeSunLastAtLongitude) - longitude);
  334. return Math.Min(time, timeSunLastAtLongitude - (MeanSpeedOfSun * longitudeErrorDelta));
  335. }
  336. // persian-new-year-on-or-before
  337. // number of days is the absolute date. The absolute date is the number of days from January 1st, 1 A.D.
  338. // 1/1/0001 is absolute date 1.
  339. internal static long PersianNewYearOnOrBefore(long numberOfDays)
  340. {
  341. double date = (double)numberOfDays;
  342. double approx = EstimatePrior(LongitudeSpring, MiddayAtPersianObservationSite(date));
  343. long lowerBoundNewYearDay = (long)Math.Floor(approx) - 1;
  344. long upperBoundNewYearDay = lowerBoundNewYearDay + 3; // estimate is generally within a day of the actual occurrence (at the limits, the error expands, since the calculations rely on the mean tropical year which changes...)
  345. long day = lowerBoundNewYearDay;
  346. for (; day != upperBoundNewYearDay; ++day)
  347. {
  348. double midday = MiddayAtPersianObservationSite((double)day);
  349. double l = Compute(midday);
  350. if ((LongitudeSpring <= l) && (l <= TwoDegreesAfterSpring))
  351. {
  352. break;
  353. }
  354. }
  355. Debug.Assert(day != upperBoundNewYearDay);
  356. return day - 1;
  357. }
  358. }
  359. }