• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* GENERATED SOURCE. DO NOT MODIFY. */
2 // © 2016 and later: Unicode, Inc. and others.
3 // License & terms of use: http://www.unicode.org/copyright.html
4 /*
5  *******************************************************************************
6  * Copyright (C) 1996-2011, International Business Machines Corporation and    *
7  * others. All Rights Reserved.                                                *
8  *******************************************************************************
9  */
10 
11 package android.icu.impl;
12 
13 import java.util.Date;
14 import java.util.TimeZone;
15 
16 /**
17  * <code>CalendarAstronomer</code> is a class that can perform the calculations to
18  * determine the positions of the sun and moon, the time of sunrise and
19  * sunset, and other astronomy-related data.  The calculations it performs
20  * are in some cases quite complicated, and this utility class saves you
21  * the trouble of worrying about them.
22  * <p>
23  * The measurement of time is a very important part of astronomy.  Because
24  * astronomical bodies are constantly in motion, observations are only valid
25  * at a given moment in time.  Accordingly, each <code>CalendarAstronomer</code>
26  * object has a <code>time</code> property that determines the date
27  * and time for which its calculations are performed.  You can set and
28  * retrieve this property with {@link #setDate setDate}, {@link #getDate getDate}
29  * and related methods.
30  * <p>
31  * Almost all of the calculations performed by this class, or by any
32  * astronomer, are approximations to various degrees of accuracy.  The
33  * calculations in this class are mostly modelled after those described
34  * in the book
35  * <a href="http://www.amazon.com/exec/obidos/ISBN=0521356997" target="_top">
36  * Practical Astronomy With Your Calculator</a>, by Peter J.
37  * Duffett-Smith, Cambridge University Press, 1990.  This is an excellent
38  * book, and if you want a greater understanding of how these calculations
39  * are performed it a very good, readable starting point.
40  * <p>
41  * <strong>WARNING:</strong> This class is very early in its development, and
42  * it is highly likely that its API will change to some degree in the future.
43  * At the moment, it basically does just enough to support {@link android.icu.util.IslamicCalendar}
44  * and {@link android.icu.util.ChineseCalendar}.
45  *
46  * @author Laura Werner
47  * @author Alan Liu
48  * @hide Only a subset of ICU is exposed in Android
49  * @hide draft / provisional / internal are hidden on Android
50  */
51 public class CalendarAstronomer {
52 
53     //-------------------------------------------------------------------------
54     // Astronomical constants
55     //-------------------------------------------------------------------------
56 
57     /**
58      * The number of standard hours in one sidereal day.
59      * Approximately 24.93.
60      * @hide draft / provisional / internal are hidden on Android
61      */
62     public static final double SIDEREAL_DAY = 23.93446960027;
63 
64     /**
65      * The number of sidereal hours in one mean solar day.
66      * Approximately 24.07.
67      * @hide draft / provisional / internal are hidden on Android
68      */
69     public static final double SOLAR_DAY =  24.065709816;
70 
71     /**
72      * The average number of solar days from one new moon to the next.  This is the time
73      * it takes for the moon to return the same ecliptic longitude as the sun.
74      * It is longer than the sidereal month because the sun's longitude increases
75      * during the year due to the revolution of the earth around the sun.
76      * Approximately 29.53.
77      *
78      * @see #SIDEREAL_MONTH
79      * @hide draft / provisional / internal are hidden on Android
80      */
81     public static final double SYNODIC_MONTH = 29.530588853;
82 
83     /**
84      * The average number of days it takes
85      * for the moon to return to the same ecliptic longitude relative to the
86      * stellar background.  This is referred to as the sidereal month.
87      * It is shorter than the synodic month due to
88      * the revolution of the earth around the sun.
89      * Approximately 27.32.
90      *
91      * @see #SYNODIC_MONTH
92      * @hide draft / provisional / internal are hidden on Android
93      */
94     public static final double SIDEREAL_MONTH = 27.32166;
95 
96     /**
97      * The average number number of days between successive vernal equinoxes.
98      * Due to the precession of the earth's
99      * axis, this is not precisely the same as the sidereal year.
100      * Approximately 365.24
101      *
102      * @see #SIDEREAL_YEAR
103      * @hide draft / provisional / internal are hidden on Android
104      */
105     public static final double TROPICAL_YEAR = 365.242191;
106 
107     /**
108      * The average number of days it takes
109      * for the sun to return to the same position against the fixed stellar
110      * background.  This is the duration of one orbit of the earth about the sun
111      * as it would appear to an outside observer.
112      * Due to the precession of the earth's
113      * axis, this is not precisely the same as the tropical year.
114      * Approximately 365.25.
115      *
116      * @see #TROPICAL_YEAR
117      * @hide draft / provisional / internal are hidden on Android
118      */
119     public static final double SIDEREAL_YEAR = 365.25636;
120 
121     //-------------------------------------------------------------------------
122     // Time-related constants
123     //-------------------------------------------------------------------------
124 
125     /**
126      * The number of milliseconds in one second.
127      * @hide draft / provisional / internal are hidden on Android
128      */
129     public static final int  SECOND_MS = 1000;
130 
131     /**
132      * The number of milliseconds in one minute.
133      * @hide draft / provisional / internal are hidden on Android
134      */
135     public static final int  MINUTE_MS = 60*SECOND_MS;
136 
137     /**
138      * The number of milliseconds in one hour.
139      * @hide draft / provisional / internal are hidden on Android
140      */
141     public static final int  HOUR_MS   = 60*MINUTE_MS;
142 
143     /**
144      * The number of milliseconds in one day.
145      * @hide draft / provisional / internal are hidden on Android
146      */
147     public static final long DAY_MS    = 24*HOUR_MS;
148 
149     /**
150      * The start of the julian day numbering scheme used by astronomers, which
151      * is 1/1/4713 BC (Julian), 12:00 GMT.  This is given as the number of milliseconds
152      * since 1/1/1970 AD (Gregorian), a negative number.
153      * Note that julian day numbers and
154      * the Julian calendar are <em>not</em> the same thing.  Also note that
155      * julian days start at <em>noon</em>, not midnight.
156      * @hide draft / provisional / internal are hidden on Android
157      */
158     public static final long JULIAN_EPOCH_MS = -210866760000000L;
159 
160 //  static {
161 //      Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
162 //      cal.clear();
163 //      cal.set(cal.ERA, 0);
164 //      cal.set(cal.YEAR, 4713);
165 //      cal.set(cal.MONTH, cal.JANUARY);
166 //      cal.set(cal.DATE, 1);
167 //      cal.set(cal.HOUR_OF_DAY, 12);
168 //      System.out.println("1.5 Jan 4713 BC = " + cal.getTime().getTime());
169 
170 //      cal.clear();
171 //      cal.set(cal.YEAR, 2000);
172 //      cal.set(cal.MONTH, cal.JANUARY);
173 //      cal.set(cal.DATE, 1);
174 //      cal.add(cal.DATE, -1);
175 //      System.out.println("0.0 Jan 2000 = " + cal.getTime().getTime());
176 //  }
177 
178     /**
179      * Milliseconds value for 0.0 January 2000 AD.
180      */
181     static final long EPOCH_2000_MS = 946598400000L;
182 
183     //-------------------------------------------------------------------------
184     // Assorted private data used for conversions
185     //-------------------------------------------------------------------------
186 
187     // My own copies of these so compilers are more likely to optimize them away
188     static private final double PI = 3.14159265358979323846;
189     static private final double PI2 = PI * 2.0;
190 
191     static private final double RAD_HOUR = 12 / PI;        // radians -> hours
192     static private final double DEG_RAD  = PI / 180;        // degrees -> radians
193     static private final double RAD_DEG  = 180 / PI;        // radians -> degrees
194 
195     //-------------------------------------------------------------------------
196     // Constructors
197     //-------------------------------------------------------------------------
198 
199     /**
200      * Construct a new <code>CalendarAstronomer</code> object that is initialized to
201      * the current date and time.
202      * @hide draft / provisional / internal are hidden on Android
203      */
CalendarAstronomer()204     public CalendarAstronomer() {
205         this(System.currentTimeMillis());
206     }
207 
208     /**
209      * Construct a new <code>CalendarAstronomer</code> object that is initialized to
210      * the specified date and time.
211      * @hide draft / provisional / internal are hidden on Android
212      */
CalendarAstronomer(Date d)213     public CalendarAstronomer(Date d) {
214         this(d.getTime());
215     }
216 
217     /**
218      * Construct a new <code>CalendarAstronomer</code> object that is initialized to
219      * the specified time.  The time is expressed as a number of milliseconds since
220      * January 1, 1970 AD (Gregorian).
221      *
222      * @see java.util.Date#getTime()
223      * @hide draft / provisional / internal are hidden on Android
224      */
CalendarAstronomer(long aTime)225     public CalendarAstronomer(long aTime) {
226         time = aTime;
227     }
228 
229     /**
230      * Construct a new <code>CalendarAstronomer</code> object with the given
231      * latitude and longitude.  The object's time is set to the current
232      * date and time.
233      * <p>
234      * @param longitude The desired longitude, in <em>degrees</em> east of
235      *                  the Greenwich meridian.
236      *
237      * @param latitude  The desired latitude, in <em>degrees</em>.  Positive
238      *                  values signify North, negative South.
239      *
240      * @see java.util.Date#getTime()
241      * @hide draft / provisional / internal are hidden on Android
242      */
CalendarAstronomer(double longitude, double latitude)243     public CalendarAstronomer(double longitude, double latitude) {
244         this();
245         fLongitude = normPI(longitude * DEG_RAD);
246         fLatitude  = normPI(latitude  * DEG_RAD);
247         fGmtOffset = (long)(fLongitude * 24 * HOUR_MS / PI2);
248     }
249 
250 
251     //-------------------------------------------------------------------------
252     // Time and date getters and setters
253     //-------------------------------------------------------------------------
254 
255     /**
256      * Set the current date and time of this <code>CalendarAstronomer</code> object.  All
257      * astronomical calculations are performed based on this time setting.
258      *
259      * @param aTime the date and time, expressed as the number of milliseconds since
260      *              1/1/1970 0:00 GMT (Gregorian).
261      *
262      * @see #setDate
263      * @see #getTime
264      * @hide draft / provisional / internal are hidden on Android
265      */
setTime(long aTime)266     public void setTime(long aTime) {
267         time = aTime;
268         clearCache();
269     }
270 
271     /**
272      * Set the current date and time of this <code>CalendarAstronomer</code> object.  All
273      * astronomical calculations are performed based on this time setting.
274      *
275      * @param date the time and date, expressed as a <code>Date</code> object.
276      *
277      * @see #setTime
278      * @see #getDate
279      * @hide draft / provisional / internal are hidden on Android
280      */
setDate(Date date)281     public void setDate(Date date) {
282         setTime(date.getTime());
283     }
284 
285     /**
286      * Set the current date and time of this <code>CalendarAstronomer</code> object.  All
287      * astronomical calculations are performed based on this time setting.
288      *
289      * @param jdn   the desired time, expressed as a "julian day number",
290      *              which is the number of elapsed days since
291      *              1/1/4713 BC (Julian), 12:00 GMT.  Note that julian day
292      *              numbers start at <em>noon</em>.  To get the jdn for
293      *              the corresponding midnight, subtract 0.5.
294      *
295      * @see #getJulianDay
296      * @see #JULIAN_EPOCH_MS
297      * @hide draft / provisional / internal are hidden on Android
298      */
setJulianDay(double jdn)299     public void setJulianDay(double jdn) {
300         time = (long)(jdn * DAY_MS) + JULIAN_EPOCH_MS;
301         clearCache();
302         julianDay = jdn;
303     }
304 
305     /**
306      * Get the current time of this <code>CalendarAstronomer</code> object,
307      * represented as the number of milliseconds since
308      * 1/1/1970 AD 0:00 GMT (Gregorian).
309      *
310      * @see #setTime
311      * @see #getDate
312      * @hide draft / provisional / internal are hidden on Android
313      */
getTime()314     public long getTime() {
315         return time;
316     }
317 
318     /**
319      * Get the current time of this <code>CalendarAstronomer</code> object,
320      * represented as a <code>Date</code> object.
321      *
322      * @see #setDate
323      * @see #getTime
324      * @hide draft / provisional / internal are hidden on Android
325      */
getDate()326     public Date getDate() {
327         return new Date(time);
328     }
329 
330     /**
331      * Get the current time of this <code>CalendarAstronomer</code> object,
332      * expressed as a "julian day number", which is the number of elapsed
333      * days since 1/1/4713 BC (Julian), 12:00 GMT.
334      *
335      * @see #setJulianDay
336      * @see #JULIAN_EPOCH_MS
337      * @hide draft / provisional / internal are hidden on Android
338      */
getJulianDay()339     public double getJulianDay() {
340         if (julianDay == INVALID) {
341             julianDay = (double)(time - JULIAN_EPOCH_MS) / (double)DAY_MS;
342         }
343         return julianDay;
344     }
345 
346     /**
347      * Return this object's time expressed in julian centuries:
348      * the number of centuries after 1/1/1900 AD, 12:00 GMT
349      *
350      * @see #getJulianDay
351      * @hide draft / provisional / internal are hidden on Android
352      */
getJulianCentury()353     public double getJulianCentury() {
354         if (julianCentury == INVALID) {
355             julianCentury = (getJulianDay() - 2415020.0) / 36525;
356         }
357         return julianCentury;
358     }
359 
360     /**
361      * Returns the current Greenwich sidereal time, measured in hours
362      * @hide draft / provisional / internal are hidden on Android
363      */
getGreenwichSidereal()364     public double getGreenwichSidereal() {
365         if (siderealTime == INVALID) {
366             // See page 86 of "Practical Astronomy with your Calculator",
367             // by Peter Duffet-Smith, for details on the algorithm.
368 
369             double UT = normalize((double)time/HOUR_MS, 24);
370 
371             siderealTime = normalize(getSiderealOffset() + UT*1.002737909, 24);
372         }
373         return siderealTime;
374     }
375 
getSiderealOffset()376     private double getSiderealOffset() {
377         if (siderealT0 == INVALID) {
378             double JD  = Math.floor(getJulianDay() - 0.5) + 0.5;
379             double S   = JD - 2451545.0;
380             double T   = S / 36525.0;
381             siderealT0 = normalize(6.697374558 + 2400.051336*T + 0.000025862*T*T, 24);
382         }
383         return siderealT0;
384     }
385 
386     /**
387      * Returns the current local sidereal time, measured in hours
388      * @hide draft / provisional / internal are hidden on Android
389      */
getLocalSidereal()390     public double getLocalSidereal() {
391         return normalize(getGreenwichSidereal() + (double)fGmtOffset/HOUR_MS, 24);
392     }
393 
394     /**
395      * Converts local sidereal time to Universal Time.
396      *
397      * @param lst   The Local Sidereal Time, in hours since sidereal midnight
398      *              on this object's current date.
399      *
400      * @return      The corresponding Universal Time, in milliseconds since
401      *              1 Jan 1970, GMT.
402      */
lstToUT(double lst)403     private long lstToUT(double lst) {
404         // Convert to local mean time
405         double lt = normalize((lst - getSiderealOffset()) * 0.9972695663, 24);
406 
407         // Then find local midnight on this day
408         long base = DAY_MS * ((time + fGmtOffset)/DAY_MS) - fGmtOffset;
409 
410         //out("    lt  =" + lt + " hours");
411         //out("    base=" + new Date(base));
412 
413         return base + (long)(lt * HOUR_MS);
414     }
415 
416 
417     //-------------------------------------------------------------------------
418     // Coordinate transformations, all based on the current time of this object
419     //-------------------------------------------------------------------------
420 
421     /**
422      * Convert from ecliptic to equatorial coordinates.
423      *
424      * @param ecliptic  A point in the sky in ecliptic coordinates.
425      * @return          The corresponding point in equatorial coordinates.
426      * @hide draft / provisional / internal are hidden on Android
427      */
eclipticToEquatorial(Ecliptic ecliptic)428     public final Equatorial eclipticToEquatorial(Ecliptic ecliptic)
429     {
430         return eclipticToEquatorial(ecliptic.longitude, ecliptic.latitude);
431     }
432 
433     /**
434      * Convert from ecliptic to equatorial coordinates.
435      *
436      * @param eclipLong     The ecliptic longitude
437      * @param eclipLat      The ecliptic latitude
438      *
439      * @return              The corresponding point in equatorial coordinates.
440      * @hide draft / provisional / internal are hidden on Android
441      */
eclipticToEquatorial(double eclipLong, double eclipLat)442     public final Equatorial eclipticToEquatorial(double eclipLong, double eclipLat)
443     {
444         // See page 42 of "Practical Astronomy with your Calculator",
445         // by Peter Duffet-Smith, for details on the algorithm.
446 
447         double obliq = eclipticObliquity();
448         double sinE = Math.sin(obliq);
449         double cosE = Math.cos(obliq);
450 
451         double sinL = Math.sin(eclipLong);
452         double cosL = Math.cos(eclipLong);
453 
454         double sinB = Math.sin(eclipLat);
455         double cosB = Math.cos(eclipLat);
456         double tanB = Math.tan(eclipLat);
457 
458         return new Equatorial(Math.atan2(sinL*cosE - tanB*sinE, cosL),
459                                Math.asin(sinB*cosE + cosB*sinE*sinL) );
460     }
461 
462     /**
463      * Convert from ecliptic longitude to equatorial coordinates.
464      *
465      * @param eclipLong     The ecliptic longitude
466      *
467      * @return              The corresponding point in equatorial coordinates.
468      * @hide draft / provisional / internal are hidden on Android
469      */
eclipticToEquatorial(double eclipLong)470     public final Equatorial eclipticToEquatorial(double eclipLong)
471     {
472         return eclipticToEquatorial(eclipLong, 0);  // TODO: optimize
473     }
474 
475     /**
476      * @hide draft / provisional / internal are hidden on Android
477      */
eclipticToHorizon(double eclipLong)478     public Horizon eclipticToHorizon(double eclipLong)
479     {
480         Equatorial equatorial = eclipticToEquatorial(eclipLong);
481 
482         double H = getLocalSidereal()*PI/12 - equatorial.ascension;     // Hour-angle
483 
484         double sinH = Math.sin(H);
485         double cosH = Math.cos(H);
486         double sinD = Math.sin(equatorial.declination);
487         double cosD = Math.cos(equatorial.declination);
488         double sinL = Math.sin(fLatitude);
489         double cosL = Math.cos(fLatitude);
490 
491         double altitude = Math.asin(sinD*sinL + cosD*cosL*cosH);
492         double azimuth  = Math.atan2(-cosD*cosL*sinH, sinD - sinL * Math.sin(altitude));
493 
494         return new Horizon(azimuth, altitude);
495     }
496 
497 
498     //-------------------------------------------------------------------------
499     // The Sun
500     //-------------------------------------------------------------------------
501 
502     //
503     // Parameters of the Sun's orbit as of the epoch Jan 0.0 1990
504     // Angles are in radians (after multiplying by PI/180)
505     //
506     static final double JD_EPOCH = 2447891.5; // Julian day of epoch
507 
508     static final double SUN_ETA_G   = 279.403303 * PI/180; // Ecliptic longitude at epoch
509     static final double SUN_OMEGA_G = 282.768422 * PI/180; // Ecliptic longitude of perigee
510     static final double SUN_E      =   0.016713;          // Eccentricity of orbit
511     //double sunR0     =   1.495585e8;        // Semi-major axis in KM
512     //double sunTheta0 =   0.533128 * PI/180; // Angular diameter at R0
513 
514     // The following three methods, which compute the sun parameters
515     // given above for an arbitrary epoch (whatever time the object is
516     // set to), make only a small difference as compared to using the
517     // above constants.  E.g., Sunset times might differ by ~12
518     // seconds.  Furthermore, the eta-g computation is befuddled by
519     // Duffet-Smith's incorrect coefficients (p.86).  I've corrected
520     // the first-order coefficient but the others may be off too - no
521     // way of knowing without consulting another source.
522 
523 //  /**
524 //   * Return the sun's ecliptic longitude at perigee for the current time.
525 //   * See Duffett-Smith, p. 86.
526 //   * @return radians
527 //   */
528 //  private double getSunOmegaG() {
529 //      double T = getJulianCentury();
530 //      return (281.2208444 + (1.719175 + 0.000452778*T)*T) * DEG_RAD;
531 //  }
532 
533 //  /**
534 //   * Return the sun's ecliptic longitude for the current time.
535 //   * See Duffett-Smith, p. 86.
536 //   * @return radians
537 //   */
538 //  private double getSunEtaG() {
539 //      double T = getJulianCentury();
540 //      //return (279.6966778 + (36000.76892 + 0.0003025*T)*T) * DEG_RAD;
541 //      //
542 //      // The above line is from Duffett-Smith, and yields manifestly wrong
543 //      // results.  The below constant is derived empirically to match the
544 //      // constant he gives for the 1990 EPOCH.
545 //      //
546 //      return (279.6966778 + (-0.3262541582718024 + 0.0003025*T)*T) * DEG_RAD;
547 //  }
548 
549 //  /**
550 //   * Return the sun's eccentricity of orbit for the current time.
551 //   * See Duffett-Smith, p. 86.
552 //   * @return double
553 //   */
554 //  private double getSunE() {
555 //      double T = getJulianCentury();
556 //      return 0.01675104 - (0.0000418 + 0.000000126*T)*T;
557 //  }
558 
559     /**
560      * The longitude of the sun at the time specified by this object.
561      * The longitude is measured in radians along the ecliptic
562      * from the "first point of Aries," the point at which the ecliptic
563      * crosses the earth's equatorial plane at the vernal equinox.
564      * <p>
565      * Currently, this method uses an approximation of the two-body Kepler's
566      * equation for the earth and the sun.  It does not take into account the
567      * perturbations caused by the other planets, the moon, etc.
568      * @hide draft / provisional / internal are hidden on Android
569      */
getSunLongitude()570     public double getSunLongitude()
571     {
572         // See page 86 of "Practical Astronomy with your Calculator",
573         // by Peter Duffet-Smith, for details on the algorithm.
574 
575         if (sunLongitude == INVALID) {
576             double[] result = getSunLongitude(getJulianDay());
577             sunLongitude = result[0];
578             meanAnomalySun = result[1];
579         }
580         return sunLongitude;
581     }
582 
583     /**
584      * TODO Make this public when the entire class is package-private.
585      */
getSunLongitude(double julian)586     /*public*/ double[] getSunLongitude(double julian)
587     {
588         // See page 86 of "Practical Astronomy with your Calculator",
589         // by Peter Duffet-Smith, for details on the algorithm.
590 
591         double day = julian - JD_EPOCH;       // Days since epoch
592 
593         // Find the angular distance the sun in a fictitious
594         // circular orbit has travelled since the epoch.
595         double epochAngle = norm2PI(PI2/TROPICAL_YEAR*day);
596 
597         // The epoch wasn't at the sun's perigee; find the angular distance
598         // since perigee, which is called the "mean anomaly"
599         double meanAnomaly = norm2PI(epochAngle + SUN_ETA_G - SUN_OMEGA_G);
600 
601         // Now find the "true anomaly", e.g. the real solar longitude
602         // by solving Kepler's equation for an elliptical orbit
603         // NOTE: The 3rd ed. of the book lists omega_g and eta_g in different
604         // equations; omega_g is to be correct.
605         return new double[] {
606             norm2PI(trueAnomaly(meanAnomaly, SUN_E) + SUN_OMEGA_G),
607             meanAnomaly
608         };
609     }
610 
611     /**
612      * The position of the sun at this object's current date and time,
613      * in equatorial coordinates.
614      * @hide draft / provisional / internal are hidden on Android
615      */
getSunPosition()616     public Equatorial getSunPosition() {
617         return eclipticToEquatorial(getSunLongitude(), 0);
618     }
619 
620     private static class SolarLongitude {
621         double value;
SolarLongitude(double val)622         SolarLongitude(double val) { value = val; }
623     }
624 
625     /**
626      * Constant representing the vernal equinox.
627      * For use with {@link #getSunTime(SolarLongitude, boolean) getSunTime}.
628      * Note: In this case, "vernal" refers to the northern hemisphere's seasons.
629      * @hide draft / provisional / internal are hidden on Android
630      */
631     public static final SolarLongitude VERNAL_EQUINOX  = new SolarLongitude(0);
632 
633     /**
634      * Constant representing the summer solstice.
635      * For use with {@link #getSunTime(SolarLongitude, boolean) getSunTime}.
636      * Note: In this case, "summer" refers to the northern hemisphere's seasons.
637      * @hide draft / provisional / internal are hidden on Android
638      */
639     public static final SolarLongitude SUMMER_SOLSTICE = new SolarLongitude(PI/2);
640 
641     /**
642      * Constant representing the autumnal equinox.
643      * For use with {@link #getSunTime(SolarLongitude, boolean) getSunTime}.
644      * Note: In this case, "autumn" refers to the northern hemisphere's seasons.
645      * @hide draft / provisional / internal are hidden on Android
646      */
647     public static final SolarLongitude AUTUMN_EQUINOX  = new SolarLongitude(PI);
648 
649     /**
650      * Constant representing the winter solstice.
651      * For use with {@link #getSunTime(SolarLongitude, boolean) getSunTime}.
652      * Note: In this case, "winter" refers to the northern hemisphere's seasons.
653      * @hide draft / provisional / internal are hidden on Android
654      */
655     public static final SolarLongitude WINTER_SOLSTICE = new SolarLongitude((PI*3)/2);
656 
657     /**
658      * Find the next time at which the sun's ecliptic longitude will have
659      * the desired value.
660      * @hide draft / provisional / internal are hidden on Android
661      */
getSunTime(double desired, boolean next)662     public long getSunTime(double desired, boolean next)
663     {
664         return timeOfAngle( new AngleFunc() { @Override
665         public double eval() { return getSunLongitude(); } },
666                             desired,
667                             TROPICAL_YEAR,
668                             MINUTE_MS,
669                             next);
670     }
671 
672     /**
673      * Find the next time at which the sun's ecliptic longitude will have
674      * the desired value.
675      * @hide draft / provisional / internal are hidden on Android
676      */
677     public long getSunTime(SolarLongitude desired, boolean next) {
678         return getSunTime(desired.value, next);
679     }
680 
681     /**
682      * Returns the time (GMT) of sunrise or sunset on the local date to which
683      * this calendar is currently set.
684      *
685      * NOTE: This method only works well if this object is set to a
686      * time near local noon.  Because of variations between the local
687      * official time zone and the geographic longitude, the
688      * computation can flop over into an adjacent day if this object
689      * is set to a time near local midnight.
690      *
691      * @hide draft / provisional / internal are hidden on Android
692      */
693     public long getSunRiseSet(boolean rise) {
694         long t0 = time;
695 
696         // Make a rough guess: 6am or 6pm local time on the current day
697         long noon = ((time + fGmtOffset)/DAY_MS)*DAY_MS - fGmtOffset + 12*HOUR_MS;
698 
699         setTime(noon + (rise ? -6L : 6L) * HOUR_MS);
700 
701         long t = riseOrSet(new CoordFunc() {
702             @Override
703             public Equatorial eval() { return getSunPosition(); }
704             },
705                 rise,
706                 .533 * DEG_RAD,        // Angular Diameter
707                 34 /60.0 * DEG_RAD,    // Refraction correction
708                 MINUTE_MS / 12);       // Desired accuracy
709 
710             setTime(t0);
711             return t;
712         }
713 
714 // Commented out - currently unused. ICU 2.6, Alan
715 //    //-------------------------------------------------------------------------
716 //    // Alternate Sun Rise/Set
717 //    // See Duffett-Smith p.93
718 //    //-------------------------------------------------------------------------
719 //
720 //    // This yields worse results (as compared to USNO data) than getSunRiseSet().
721 //    /**
722 //     * TODO Make this public when the entire class is package-private.
723 //     */
724 //    /*public*/ long getSunRiseSet2(boolean rise) {
725 //        // 1. Calculate coordinates of the sun's center for midnight
726 //        double jd = Math.floor(getJulianDay() - 0.5) + 0.5;
727 //        double[] sl = getSunLongitude(jd);
728 //        double lambda1 = sl[0];
729 //        Equatorial pos1 = eclipticToEquatorial(lambda1, 0);
730 //
731 //        // 2. Add ... to lambda to get position 24 hours later
732 //        double lambda2 = lambda1 + 0.985647*DEG_RAD;
733 //        Equatorial pos2 = eclipticToEquatorial(lambda2, 0);
734 //
735 //        // 3. Calculate LSTs of rising and setting for these two positions
736 //        double tanL = Math.tan(fLatitude);
737 //        double H = Math.acos(-tanL * Math.tan(pos1.declination));
738 //        double lst1r = (PI2 + pos1.ascension - H) * 24 / PI2;
739 //        double lst1s = (pos1.ascension + H) * 24 / PI2;
740 //               H = Math.acos(-tanL * Math.tan(pos2.declination));
741 //        double lst2r = (PI2-H + pos2.ascension ) * 24 / PI2;
742 //        double lst2s = (H + pos2.ascension ) * 24 / PI2;
743 //        if (lst1r > 24) lst1r -= 24;
744 //        if (lst1s > 24) lst1s -= 24;
745 //        if (lst2r > 24) lst2r -= 24;
746 //        if (lst2s > 24) lst2s -= 24;
747 //
748 //        // 4. Convert LSTs to GSTs.  If GST1 > GST2, add 24 to GST2.
749 //        double gst1r = lstToGst(lst1r);
750 //        double gst1s = lstToGst(lst1s);
751 //        double gst2r = lstToGst(lst2r);
752 //        double gst2s = lstToGst(lst2s);
753 //        if (gst1r > gst2r) gst2r += 24;
754 //        if (gst1s > gst2s) gst2s += 24;
755 //
756 //        // 5. Calculate GST at 0h UT of this date
757 //        double t00 = utToGst(0);
758 //
759 //        // 6. Calculate GST at 0h on the observer's longitude
760 //        double offset = Math.round(fLongitude*12/PI); // p.95 step 6; he _rounds_ to nearest 15 deg.
761 //        double t00p = t00 - offset*1.002737909;
762 //        if (t00p < 0) t00p += 24; // do NOT normalize
763 //
764 //        // 7. Adjust
765 //        if (gst1r < t00p) {
766 //            gst1r += 24;
767 //            gst2r += 24;
768 //        }
769 //        if (gst1s < t00p) {
770 //            gst1s += 24;
771 //            gst2s += 24;
772 //        }
773 //
774 //        // 8.
775 //        double gstr = (24.07*gst1r-t00*(gst2r-gst1r))/(24.07+gst1r-gst2r);
776 //        double gsts = (24.07*gst1s-t00*(gst2s-gst1s))/(24.07+gst1s-gst2s);
777 //
778 //        // 9. Correct for parallax, refraction, and sun's diameter
779 //        double dec = (pos1.declination + pos2.declination) / 2;
780 //        double psi = Math.acos(Math.sin(fLatitude) / Math.cos(dec));
781 //        double x = 0.830725 * DEG_RAD; // parallax+refraction+diameter
782 //        double y = Math.asin(Math.sin(x) / Math.sin(psi)) * RAD_DEG;
783 //        double delta_t = 240 * y / Math.cos(dec) / 3600; // hours
784 //
785 //        // 10. Add correction to GSTs, subtract from GSTr
786 //        gstr -= delta_t;
787 //        gsts += delta_t;
788 //
789 //        // 11. Convert GST to UT and then to local civil time
790 //        double ut = gstToUt(rise ? gstr : gsts);
791 //        //System.out.println((rise?"rise=":"set=") + ut + ", delta_t=" + delta_t);
792 //        long midnight = DAY_MS * (time / DAY_MS); // Find UT midnight on this day
793 //        return midnight + (long) (ut * 3600000);
794 //    }
795 
796 // Commented out - currently unused. ICU 2.6, Alan
797 //    /**
798 //     * Convert local sidereal time to Greenwich sidereal time.
799 //     * Section 15.  Duffett-Smith p.21
800 //     * @param lst in hours (0..24)
801 //     * @return GST in hours (0..24)
802 //     */
803 //    double lstToGst(double lst) {
804 //        double delta = fLongitude * 24 / PI2;
805 //        return normalize(lst - delta, 24);
806 //    }
807 
808 // Commented out - currently unused. ICU 2.6, Alan
809 //    /**
810 //     * Convert UT to GST on this date.
811 //     * Section 12.  Duffett-Smith p.17
812 //     * @param ut in hours
813 //     * @return GST in hours
814 //     */
815 //    double utToGst(double ut) {
816 //        return normalize(getT0() + ut*1.002737909, 24);
817 //    }
818 
819 // Commented out - currently unused. ICU 2.6, Alan
820 //    /**
821 //     * Convert GST to UT on this date.
822 //     * Section 13.  Duffett-Smith p.18
823 //     * @param gst in hours
824 //     * @return UT in hours
825 //     */
826 //    double gstToUt(double gst) {
827 //        return normalize(gst - getT0(), 24) * 0.9972695663;
828 //    }
829 
830 // Commented out - currently unused. ICU 2.6, Alan
831 //    double getT0() {
832 //        // Common computation for UT <=> GST
833 //
834 //        // Find JD for 0h UT
835 //        double jd = Math.floor(getJulianDay() - 0.5) + 0.5;
836 //
837 //        double s = jd - 2451545.0;
838 //        double t = s / 36525.0;
839 //        double t0 = 6.697374558 + (2400.051336 + 0.000025862*t)*t;
840 //        return t0;
841 //    }
842 
843 // Commented out - currently unused. ICU 2.6, Alan
844 //    //-------------------------------------------------------------------------
845 //    // Alternate Sun Rise/Set
846 //    // See sci.astro FAQ
847 //    // http://www.faqs.org/faqs/astronomy/faq/part3/section-5.html
848 //    //-------------------------------------------------------------------------
849 //
850 //    // Note: This method appears to produce inferior accuracy as
851 //    // compared to getSunRiseSet().
852 //
853 //    /**
854 //     * TODO Make this public when the entire class is package-private.
855 //     */
856 //    /*public*/ long getSunRiseSet3(boolean rise) {
857 //
858 //        // Compute day number for 0.0 Jan 2000 epoch
859 //        double d = (double)(time - EPOCH_2000_MS) / DAY_MS;
860 //
861 //        // Now compute the Local Sidereal Time, LST:
862 //        //
863 //        double LST  =  98.9818  +  0.985647352 * d  +  /*UT*15  +  long*/
864 //            fLongitude*RAD_DEG;
865 //        //
866 //        // (east long. positive).  Note that LST is here expressed in degrees,
867 //        // where 15 degrees corresponds to one hour.  Since LST really is an angle,
868 //        // it's convenient to use one unit---degrees---throughout.
869 //
870 //        //     COMPUTING THE SUN'S POSITION
871 //        //     ----------------------------
872 //        //
873 //        // To be able to compute the Sun's rise/set times, you need to be able to
874 //        // compute the Sun's position at any time.  First compute the "day
875 //        // number" d as outlined above, for the desired moment.  Next compute:
876 //        //
877 //        double oblecl = 23.4393 - 3.563E-7 * d;
878 //        //
879 //        double w  =  282.9404  +  4.70935E-5   * d;
880 //        double M  =  356.0470  +  0.9856002585 * d;
881 //        double e  =  0.016709  -  1.151E-9     * d;
882 //        //
883 //        // This is the obliquity of the ecliptic, plus some of the elements of
884 //        // the Sun's apparent orbit (i.e., really the Earth's orbit): w =
885 //        // argument of perihelion, M = mean anomaly, e = eccentricity.
886 //        // Semi-major axis is here assumed to be exactly 1.0 (while not strictly
887 //        // true, this is still an accurate approximation).  Next compute E, the
888 //        // eccentric anomaly:
889 //        //
890 //        double E = M + e*(180/PI) * Math.sin(M*DEG_RAD) * ( 1.0 + e*Math.cos(M*DEG_RAD) );
891 //        //
892 //        // where E and M are in degrees.  This is it---no further iterations are
893 //        // needed because we know e has a sufficiently small value.  Next compute
894 //        // the true anomaly, v, and the distance, r:
895 //        //
896 //        /*      r * cos(v)  =  */ double A  =  Math.cos(E*DEG_RAD) - e;
897 //        /*      r * sin(v)  =  */ double B  =  Math.sqrt(1 - e*e) * Math.sin(E*DEG_RAD);
898 //        //
899 //        // and
900 //        //
901 //        //      r  =  sqrt( A*A + B*B )
902 //        double v  =  Math.atan2( B, A )*RAD_DEG;
903 //        //
904 //        // The Sun's true longitude, slon, can now be computed:
905 //        //
906 //        double slon  =  v + w;
907 //        //
908 //        // Since the Sun is always at the ecliptic (or at least very very close to
909 //        // it), we can use simplified formulae to convert slon (the Sun's ecliptic
910 //        // longitude) to sRA and sDec (the Sun's RA and Dec):
911 //        //
912 //        //                   sin(slon) * cos(oblecl)
913 //        //     tan(sRA)  =  -------------------------
914 //        //             cos(slon)
915 //        //
916 //        //     sin(sDec) =  sin(oblecl) * sin(slon)
917 //        //
918 //        // As was the case when computing az, the Azimuth, if possible use an
919 //        // atan2() function to compute sRA.
920 //
921 //        double sRA = Math.atan2(Math.sin(slon*DEG_RAD) * Math.cos(oblecl*DEG_RAD), Math.cos(slon*DEG_RAD))*RAD_DEG;
922 //
923 //        double sin_sDec = Math.sin(oblecl*DEG_RAD) * Math.sin(slon*DEG_RAD);
924 //        double sDec = Math.asin(sin_sDec)*RAD_DEG;
925 //
926 //        //     COMPUTING RISE AND SET TIMES
927 //        //     ----------------------------
928 //        //
929 //        // To compute when an object rises or sets, you must compute when it
930 //        // passes the meridian and the HA of rise/set.  Then the rise time is
931 //        // the meridian time minus HA for rise/set, and the set time is the
932 //        // meridian time plus the HA for rise/set.
933 //        //
934 //        // To find the meridian time, compute the Local Sidereal Time at 0h local
935 //        // time (or 0h UT if you prefer to work in UT) as outlined above---name
936 //        // that quantity LST0.  The Meridian Time, MT, will now be:
937 //        //
938 //        //     MT  =  RA - LST0
939 //        double MT = normalize(sRA - LST, 360);
940 //        //
941 //        // where "RA" is the object's Right Ascension (in degrees!).  If negative,
942 //        // add 360 deg to MT.  If the object is the Sun, leave the time as it is,
943 //        // but if it's stellar, multiply MT by 365.2422/366.2422, to convert from
944 //        // sidereal to solar time.  Now, compute HA for rise/set, name that
945 //        // quantity HA0:
946 //        //
947 //        //                 sin(h0)  -  sin(lat) * sin(Dec)
948 //        // cos(HA0)  =  ---------------------------------
949 //        //                      cos(lat) * cos(Dec)
950 //        //
951 //        // where h0 is the altitude selected to represent rise/set.  For a purely
952 //        // mathematical horizon, set h0 = 0 and simplify to:
953 //        //
954 //        //     cos(HA0)  =  - tan(lat) * tan(Dec)
955 //        //
956 //        // If you want to account for refraction on the atmosphere, set h0 = -35/60
957 //        // degrees (-35 arc minutes), and if you want to compute the rise/set times
958 //        // for the Sun's upper limb, set h0 = -50/60 (-50 arc minutes).
959 //        //
960 //        double h0 = -50/60 * DEG_RAD;
961 //
962 //        double HA0 = Math.acos(
963 //          (Math.sin(h0) - Math.sin(fLatitude) * sin_sDec) /
964 //          (Math.cos(fLatitude) * Math.cos(sDec*DEG_RAD)))*RAD_DEG;
965 //
966 //        // When HA0 has been computed, leave it as it is for the Sun but multiply
967 //        // by 365.2422/366.2422 for stellar objects, to convert from sidereal to
968 //        // solar time.  Finally compute:
969 //        //
970 //        //    Rise time  =  MT - HA0
971 //        //    Set  time  =  MT + HA0
972 //        //
973 //        // convert the times from degrees to hours by dividing by 15.
974 //        //
975 //        // If you'd like to check that your calculations are accurate or just
976 //        // need a quick result, check the USNO's Sun or Moon Rise/Set Table,
977 //        // <URL:http://aa.usno.navy.mil/AA/data/docs/RS_OneYear.html>.
978 //
979 //        double result = MT + (rise ? -HA0 : HA0); // in degrees
980 //
981 //        // Find UT midnight on this day
982 //        long midnight = DAY_MS * (time / DAY_MS);
983 //
984 //        return midnight + (long) (result * 3600000 / 15);
985 //    }
986 
987     //-------------------------------------------------------------------------
988     // The Moon
989     //-------------------------------------------------------------------------
990 
991     static final double moonL0 = 318.351648 * PI/180;   // Mean long. at epoch
992     static final double moonP0 =  36.340410 * PI/180;   // Mean long. of perigee
993     static final double moonN0 = 318.510107 * PI/180;   // Mean long. of node
994     static final double moonI  =   5.145366 * PI/180;   // Inclination of orbit
995     static final double moonE  =   0.054900;            // Eccentricity of orbit
996 
997     // These aren't used right now
998     static final double moonA  =   3.84401e5;           // semi-major axis (km)
999     static final double moonT0 =   0.5181 * PI/180;     // Angular size at distance A
1000     static final double moonPi =   0.9507 * PI/180;     // Parallax at distance A
1001 
1002     /**
1003      * The position of the moon at the time set on this
1004      * object, in equatorial coordinates.
1005      * @hide draft / provisional / internal are hidden on Android
1006      */
1007     public Equatorial getMoonPosition()
1008     {
1009         //
1010         // See page 142 of "Practical Astronomy with your Calculator",
1011         // by Peter Duffet-Smith, for details on the algorithm.
1012         //
1013         if (moonPosition == null) {
1014             // Calculate the solar longitude.  Has the side effect of
1015             // filling in "meanAnomalySun" as well.
1016             double sunLong = getSunLongitude();
1017 
1018             //
1019             // Find the # of days since the epoch of our orbital parameters.
1020             // TODO: Convert the time of day portion into ephemeris time
1021             //
1022             double day = getJulianDay() - JD_EPOCH;       // Days since epoch
1023 
1024             // Calculate the mean longitude and anomaly of the moon, based on
1025             // a circular orbit.  Similar to the corresponding solar calculation.
1026             double meanLongitude = norm2PI(13.1763966*PI/180*day + moonL0);
1027             double meanAnomalyMoon = norm2PI(meanLongitude - 0.1114041*PI/180 * day - moonP0);
1028 
1029             //
1030             // Calculate the following corrections:
1031             //  Evection:   the sun's gravity affects the moon's eccentricity
1032             //  Annual Eqn: variation in the effect due to earth-sun distance
1033             //  A3:         correction factor (for ???)
1034             //
1035             double evection = 1.2739*PI/180 * Math.sin(2 * (meanLongitude - sunLong)
1036                                                 - meanAnomalyMoon);
1037             double annual   = 0.1858*PI/180 * Math.sin(meanAnomalySun);
1038             double a3       = 0.3700*PI/180 * Math.sin(meanAnomalySun);
1039 
1040             meanAnomalyMoon += evection - annual - a3;
1041 
1042             //
1043             // More correction factors:
1044             //  center  equation of the center correction
1045             //  a4      yet another error correction (???)
1046             //
1047             // TODO: Skip the equation of the center correction and solve Kepler's eqn?
1048             //
1049             double center = 6.2886*PI/180 * Math.sin(meanAnomalyMoon);
1050             double a4 =     0.2140*PI/180 * Math.sin(2 * meanAnomalyMoon);
1051 
1052             // Now find the moon's corrected longitude
1053             moonLongitude = meanLongitude + evection + center - annual + a4;
1054 
1055             //
1056             // And finally, find the variation, caused by the fact that the sun's
1057             // gravitational pull on the moon varies depending on which side of
1058             // the earth the moon is on
1059             //
1060             double variation = 0.6583*PI/180 * Math.sin(2*(moonLongitude - sunLong));
1061 
1062             moonLongitude += variation;
1063 
1064             //
1065             // What we've calculated so far is the moon's longitude in the plane
1066             // of its own orbit.  Now map to the ecliptic to get the latitude
1067             // and longitude.  First we need to find the longitude of the ascending
1068             // node, the position on the ecliptic where it is crossed by the moon's
1069             // orbit as it crosses from the southern to the northern hemisphere.
1070             //
1071             double nodeLongitude = norm2PI(moonN0 - 0.0529539*PI/180 * day);
1072 
1073             nodeLongitude -= 0.16*PI/180 * Math.sin(meanAnomalySun);
1074 
1075             double y = Math.sin(moonLongitude - nodeLongitude);
1076             double x = Math.cos(moonLongitude - nodeLongitude);
1077 
1078             moonEclipLong = Math.atan2(y*Math.cos(moonI), x) + nodeLongitude;
1079             double moonEclipLat = Math.asin(y * Math.sin(moonI));
1080 
1081             moonPosition = eclipticToEquatorial(moonEclipLong, moonEclipLat);
1082         }
1083         return moonPosition;
1084     }
1085 
1086     /**
1087      * The "age" of the moon at the time specified in this object.
1088      * This is really the angle between the
1089      * current ecliptic longitudes of the sun and the moon,
1090      * measured in radians.
1091      *
1092      * @see #getMoonPhase
1093      * @hide draft / provisional / internal are hidden on Android
1094      */
1095     public double getMoonAge() {
1096         // See page 147 of "Practical Astronomy with your Calculator",
1097         // by Peter Duffet-Smith, for details on the algorithm.
1098         //
1099         // Force the moon's position to be calculated.  We're going to use
1100         // some the intermediate results cached during that calculation.
1101         //
1102         getMoonPosition();
1103 
1104         return norm2PI(moonEclipLong - sunLongitude);
1105     }
1106 
1107     /**
1108      * Calculate the phase of the moon at the time set in this object.
1109      * The returned phase is a <code>double</code> in the range
1110      * <code>0 <= phase < 1</code>, interpreted as follows:
1111      * <ul>
1112      * <li>0.00: New moon
1113      * <li>0.25: First quarter
1114      * <li>0.50: Full moon
1115      * <li>0.75: Last quarter
1116      * </ul>
1117      *
1118      * @see #getMoonAge
1119      * @hide draft / provisional / internal are hidden on Android
1120      */
1121     public double getMoonPhase() {
1122         // See page 147 of "Practical Astronomy with your Calculator",
1123         // by Peter Duffet-Smith, for details on the algorithm.
1124         return 0.5 * (1 - Math.cos(getMoonAge()));
1125     }
1126 
1127     private static class MoonAge {
1128         double value;
1129         MoonAge(double val) { value = val; }
1130     }
1131 
1132     /**
1133      * Constant representing a new moon.
1134      * For use with {@link #getMoonTime(MoonAge, boolean) getMoonTime}
1135      * @hide draft / provisional / internal are hidden on Android
1136      */
1137     public static final MoonAge NEW_MOON      = new MoonAge(0);
1138 
1139     /**
1140      * Constant representing the moon's first quarter.
1141      * For use with {@link #getMoonTime(MoonAge, boolean) getMoonTime}
1142      * @hide draft / provisional / internal are hidden on Android
1143      */
1144     public static final MoonAge FIRST_QUARTER = new MoonAge(PI/2);
1145 
1146     /**
1147      * Constant representing a full moon.
1148      * For use with {@link #getMoonTime(MoonAge, boolean) getMoonTime}
1149      * @hide draft / provisional / internal are hidden on Android
1150      */
1151     public static final MoonAge FULL_MOON     = new MoonAge(PI);
1152 
1153     /**
1154      * Constant representing the moon's last quarter.
1155      * For use with {@link #getMoonTime(MoonAge, boolean) getMoonTime}
1156      * @hide draft / provisional / internal are hidden on Android
1157      */
1158     public static final MoonAge LAST_QUARTER  = new MoonAge((PI*3)/2);
1159 
1160     /**
1161      * Find the next or previous time at which the Moon's ecliptic
1162      * longitude will have the desired value.
1163      * <p>
1164      * @param desired   The desired longitude.
1165      * @param next      <tt>true</tt> if the next occurrance of the phase
1166      *                  is desired, <tt>false</tt> for the previous occurrance.
1167      * @hide draft / provisional / internal are hidden on Android
1168      */
1169     public long getMoonTime(double desired, boolean next)
1170     {
1171         return timeOfAngle( new AngleFunc() {
1172                             @Override
1173                             public double eval() { return getMoonAge(); } },
1174                             desired,
1175                             SYNODIC_MONTH,
1176                             MINUTE_MS,
1177                             next);
1178     }
1179 
1180     /**
1181      * Find the next or previous time at which the moon will be in the
1182      * desired phase.
1183      * <p>
1184      * @param desired   The desired phase of the moon.
1185      * @param next      <tt>true</tt> if the next occurrance of the phase
1186      *                  is desired, <tt>false</tt> for the previous occurrance.
1187      * @hide draft / provisional / internal are hidden on Android
1188      */
1189     public long getMoonTime(MoonAge desired, boolean next) {
1190         return getMoonTime(desired.value, next);
1191     }
1192 
1193     /**
1194      * Returns the time (GMT) of sunrise or sunset on the local date to which
1195      * this calendar is currently set.
1196      * @hide draft / provisional / internal are hidden on Android
1197      */
1198     public long getMoonRiseSet(boolean rise)
1199     {
1200         return riseOrSet(new CoordFunc() {
1201                             @Override
1202                             public Equatorial eval() { return getMoonPosition(); }
1203                          },
1204                          rise,
1205                          .533 * DEG_RAD,        // Angular Diameter
1206                          34 /60.0 * DEG_RAD,    // Refraction correction
1207                          MINUTE_MS);            // Desired accuracy
1208     }
1209 
1210     //-------------------------------------------------------------------------
1211     // Interpolation methods for finding the time at which a given event occurs
1212     //-------------------------------------------------------------------------
1213 
1214     private interface AngleFunc {
1215         public double eval();
1216     }
1217 
1218     private long timeOfAngle(AngleFunc func, double desired,
1219                              double periodDays, long epsilon, boolean next)
1220     {
1221         // Find the value of the function at the current time
1222         double lastAngle = func.eval();
1223 
1224         // Find out how far we are from the desired angle
1225         double deltaAngle = norm2PI(desired - lastAngle) ;
1226 
1227         // Using the average period, estimate the next (or previous) time at
1228         // which the desired angle occurs.
1229         double deltaT =  (deltaAngle + (next ? 0 : -PI2)) * (periodDays*DAY_MS) / PI2;
1230 
1231         double lastDeltaT = deltaT; // Liu
1232         long startTime = time; // Liu
1233 
1234         setTime(time + (long)deltaT);
1235 
1236         // Now iterate until we get the error below epsilon.  Throughout
1237         // this loop we use normPI to get values in the range -Pi to Pi,
1238         // since we're using them as correction factors rather than absolute angles.
1239         do {
1240             // Evaluate the function at the time we've estimated
1241             double angle = func.eval();
1242 
1243             // Find the # of milliseconds per radian at this point on the curve
1244             double factor = Math.abs(deltaT / normPI(angle-lastAngle));
1245 
1246             // Correct the time estimate based on how far off the angle is
1247             deltaT = normPI(desired - angle) * factor;
1248 
1249             // HACK:
1250             //
1251             // If abs(deltaT) begins to diverge we need to quit this loop.
1252             // This only appears to happen when attempting to locate, for
1253             // example, a new moon on the day of the new moon.  E.g.:
1254             //
1255             // This result is correct:
1256             // newMoon(7508(Mon Jul 23 00:00:00 CST 1990,false))=
1257             //   Sun Jul 22 10:57:41 CST 1990
1258             //
1259             // But attempting to make the same call a day earlier causes deltaT
1260             // to diverge:
1261             // CalendarAstronomer.timeOfAngle() diverging: 1.348508727575625E9 ->
1262             //   1.3649828540224032E9
1263             // newMoon(7507(Sun Jul 22 00:00:00 CST 1990,false))=
1264             //   Sun Jul 08 13:56:15 CST 1990
1265             //
1266             // As a temporary solution, we catch this specific condition and
1267             // adjust our start time by one eighth period days (either forward
1268             // or backward) and try again.
1269             // Liu 11/9/00
1270             if (Math.abs(deltaT) > Math.abs(lastDeltaT)) {
1271                 long delta = (long) (periodDays * DAY_MS / 8);
1272                 setTime(startTime + (next ? delta : -delta));
1273                 return timeOfAngle(func, desired, periodDays, epsilon, next);
1274             }
1275 
1276             lastDeltaT = deltaT;
1277             lastAngle = angle;
1278 
1279             setTime(time + (long)deltaT);
1280         }
1281         while (Math.abs(deltaT) > epsilon);
1282 
1283         return time;
1284     }
1285 
1286     private interface CoordFunc {
1287         public Equatorial eval();
1288     }
1289 
1290     private long riseOrSet(CoordFunc func, boolean rise,
1291                            double diameter, double refraction,
1292                            long epsilon)
1293     {
1294         Equatorial  pos = null;
1295         double      tanL   = Math.tan(fLatitude);
1296         long        deltaT = Long.MAX_VALUE;
1297         int         count = 0;
1298 
1299         //
1300         // Calculate the object's position at the current time, then use that
1301         // position to calculate the time of rising or setting.  The position
1302         // will be different at that time, so iterate until the error is allowable.
1303         //
1304         do {
1305             // See "Practical Astronomy With Your Calculator, section 33.
1306             pos = func.eval();
1307             double angle = Math.acos(-tanL * Math.tan(pos.declination));
1308             double lst = ((rise ? PI2-angle : angle) + pos.ascension ) * 24 / PI2;
1309 
1310             // Convert from LST to Universal Time.
1311             long newTime = lstToUT( lst );
1312 
1313             deltaT = newTime - time;
1314             setTime(newTime);
1315         }
1316         while (++ count < 5 && Math.abs(deltaT) > epsilon);
1317 
1318         // Calculate the correction due to refraction and the object's angular diameter
1319         double cosD  = Math.cos(pos.declination);
1320         double psi   = Math.acos(Math.sin(fLatitude) / cosD);
1321         double x     = diameter / 2 + refraction;
1322         double y     = Math.asin(Math.sin(x) / Math.sin(psi));
1323         long  delta  = (long)((240 * y * RAD_DEG / cosD)*SECOND_MS);
1324 
1325         return time + (rise ? -delta : delta);
1326     }
1327 
1328     //-------------------------------------------------------------------------
1329     // Other utility methods
1330     //-------------------------------------------------------------------------
1331 
1332     /***
1333      * Given 'value', add or subtract 'range' until 0 <= 'value' < range.
1334      * The modulus operator.
1335      */
1336     private static final double normalize(double value, double range) {
1337         return value - range * Math.floor(value / range);
1338     }
1339 
1340     /**
1341      * Normalize an angle so that it's in the range 0 - 2pi.
1342      * For positive angles this is just (angle % 2pi), but the Java
1343      * mod operator doesn't work that way for negative numbers....
1344      */
1345     private static final double norm2PI(double angle) {
1346         return normalize(angle, PI2);
1347     }
1348 
1349     /**
1350      * Normalize an angle into the range -PI - PI
1351      */
1352     private static final double normPI(double angle) {
1353         return normalize(angle + PI, PI2) - PI;
1354     }
1355 
1356     /**
1357      * Find the "true anomaly" (longitude) of an object from
1358      * its mean anomaly and the eccentricity of its orbit.  This uses
1359      * an iterative solution to Kepler's equation.
1360      *
1361      * @param meanAnomaly   The object's longitude calculated as if it were in
1362      *                      a regular, circular orbit, measured in radians
1363      *                      from the point of perigee.
1364      *
1365      * @param eccentricity  The eccentricity of the orbit
1366      *
1367      * @return The true anomaly (longitude) measured in radians
1368      */
1369     private double trueAnomaly(double meanAnomaly, double eccentricity)
1370     {
1371         // First, solve Kepler's equation iteratively
1372         // Duffett-Smith, p.90
1373         double delta;
1374         double E = meanAnomaly;
1375         do {
1376             delta = E - eccentricity * Math.sin(E) - meanAnomaly;
1377             E = E - delta / (1 - eccentricity * Math.cos(E));
1378         }
1379         while (Math.abs(delta) > 1e-5); // epsilon = 1e-5 rad
1380 
1381         return 2.0 * Math.atan( Math.tan(E/2) * Math.sqrt( (1+eccentricity)
1382                                                           /(1-eccentricity) ) );
1383     }
1384 
1385     /**
1386      * Return the obliquity of the ecliptic (the angle between the ecliptic
1387      * and the earth's equator) at the current time.  This varies due to
1388      * the precession of the earth's axis.
1389      *
1390      * @return  the obliquity of the ecliptic relative to the equator,
1391      *          measured in radians.
1392      */
1393     private double eclipticObliquity() {
1394         if (eclipObliquity == INVALID) {
1395             final double epoch = 2451545.0;     // 2000 AD, January 1.5
1396 
1397             double T = (getJulianDay() - epoch) / 36525;
1398 
1399             eclipObliquity = 23.439292
1400                            - 46.815/3600 * T
1401                            - 0.0006/3600 * T*T
1402                            + 0.00181/3600 * T*T*T;
1403 
1404             eclipObliquity *= DEG_RAD;
1405         }
1406         return eclipObliquity;
1407     }
1408 
1409 
1410     //-------------------------------------------------------------------------
1411     // Private data
1412     //-------------------------------------------------------------------------
1413 
1414     /**
1415      * Current time in milliseconds since 1/1/1970 AD
1416      * @see java.util.Date#getTime
1417      */
1418     private long time;
1419 
1420     /* These aren't used yet, but they'll be needed for sunset calculations
1421      * and equatorial to horizon coordinate conversions
1422      */
1423     private double fLongitude = 0.0;
1424     private double fLatitude  = 0.0;
1425     private long   fGmtOffset = 0;
1426 
1427     //
1428     // The following fields are used to cache calculated results for improved
1429     // performance.  These values all depend on the current time setting
1430     // of this object, so the clearCache method is provided.
1431     //
1432     static final private double INVALID = Double.MIN_VALUE;
1433 
1434     private transient double    julianDay       = INVALID;
1435     private transient double    julianCentury   = INVALID;
1436     private transient double    sunLongitude    = INVALID;
1437     private transient double    meanAnomalySun  = INVALID;
1438     private transient double    moonLongitude   = INVALID;
1439     private transient double    moonEclipLong   = INVALID;
1440     //private transient double    meanAnomalyMoon = INVALID;
1441     private transient double    eclipObliquity  = INVALID;
1442     private transient double    siderealT0      = INVALID;
1443     private transient double    siderealTime    = INVALID;
1444 
1445     private transient Equatorial  moonPosition = null;
1446 
1447     private void clearCache() {
1448         julianDay       = INVALID;
1449         julianCentury   = INVALID;
1450         sunLongitude    = INVALID;
1451         meanAnomalySun  = INVALID;
1452         moonLongitude   = INVALID;
1453         moonEclipLong   = INVALID;
1454         //meanAnomalyMoon = INVALID;
1455         eclipObliquity  = INVALID;
1456         siderealTime    = INVALID;
1457         siderealT0      = INVALID;
1458         moonPosition    = null;
1459     }
1460 
1461     //private static void out(String s) {
1462     //    System.out.println(s);
1463     //}
1464 
1465     //private static String deg(double rad) {
1466     //    return Double.toString(rad * RAD_DEG);
1467     //}
1468 
1469     //private static String hours(long ms) {
1470     //    return Double.toString((double)ms / HOUR_MS) + " hours";
1471     //}
1472 
1473     /**
1474      * @hide draft / provisional / internal are hidden on Android
1475      */
1476     public String local(long localMillis) {
1477         return new Date(localMillis - TimeZone.getDefault().getRawOffset()).toString();
1478     }
1479 
1480 
1481     /**
1482      * Represents the position of an object in the sky relative to the ecliptic,
1483      * the plane of the earth's orbit around the Sun.
1484      * This is a spherical coordinate system in which the latitude
1485      * specifies the position north or south of the plane of the ecliptic.
1486      * The longitude specifies the position along the ecliptic plane
1487      * relative to the "First Point of Aries", which is the Sun's position in the sky
1488      * at the Vernal Equinox.
1489      * <p>
1490      * Note that Ecliptic objects are immutable and cannot be modified
1491      * once they are constructed.  This allows them to be passed and returned by
1492      * value without worrying about whether other code will modify them.
1493      *
1494      * @see CalendarAstronomer.Equatorial
1495      * @see CalendarAstronomer.Horizon
1496      * @hide Only a subset of ICU is exposed in Android
1497      * @hide draft / provisional / internal are hidden on Android
1498      */
1499     public static final class Ecliptic {
1500         /**
1501          * Constructs an Ecliptic coordinate object.
1502          * <p>
1503          * @param lat The ecliptic latitude, measured in radians.
1504          * @param lon The ecliptic longitude, measured in radians.
1505          * @hide draft / provisional / internal are hidden on Android
1506          */
1507         public Ecliptic(double lat, double lon) {
1508             latitude = lat;
1509             longitude = lon;
1510         }
1511 
1512         /**
1513          * Return a string representation of this object
1514          * @hide draft / provisional / internal are hidden on Android
1515          */
1516         @Override
1517         public String toString() {
1518             return Double.toString(longitude*RAD_DEG) + "," + (latitude*RAD_DEG);
1519         }
1520 
1521         /**
1522          * The ecliptic latitude, in radians.  This specifies an object's
1523          * position north or south of the plane of the ecliptic,
1524          * with positive angles representing north.
1525          * @hide draft / provisional / internal are hidden on Android
1526          */
1527         public final double latitude;
1528 
1529         /**
1530          * The ecliptic longitude, in radians.
1531          * This specifies an object's position along the ecliptic plane
1532          * relative to the "First Point of Aries", which is the Sun's position
1533          * in the sky at the Vernal Equinox,
1534          * with positive angles representing east.
1535          * <p>
1536          * A bit of trivia: the first point of Aries is currently in the
1537          * constellation Pisces, due to the precession of the earth's axis.
1538          * @hide draft / provisional / internal are hidden on Android
1539          */
1540         public final double longitude;
1541     }
1542 
1543     /**
1544      * Represents the position of an
1545      * object in the sky relative to the plane of the earth's equator.
1546      * The <i>Right Ascension</i> specifies the position east or west
1547      * along the equator, relative to the sun's position at the vernal
1548      * equinox.  The <i>Declination</i> is the position north or south
1549      * of the equatorial plane.
1550      * <p>
1551      * Note that Equatorial objects are immutable and cannot be modified
1552      * once they are constructed.  This allows them to be passed and returned by
1553      * value without worrying about whether other code will modify them.
1554      *
1555      * @see CalendarAstronomer.Ecliptic
1556      * @see CalendarAstronomer.Horizon
1557      * @hide Only a subset of ICU is exposed in Android
1558      * @hide draft / provisional / internal are hidden on Android
1559      */
1560     public static final class Equatorial {
1561         /**
1562          * Constructs an Equatorial coordinate object.
1563          * <p>
1564          * @param asc The right ascension, measured in radians.
1565          * @param dec The declination, measured in radians.
1566          * @hide draft / provisional / internal are hidden on Android
1567          */
1568         public Equatorial(double asc, double dec) {
1569             ascension = asc;
1570             declination = dec;
1571         }
1572 
1573         /**
1574          * Return a string representation of this object, with the
1575          * angles measured in degrees.
1576          * @hide draft / provisional / internal are hidden on Android
1577          */
1578         @Override
1579         public String toString() {
1580             return Double.toString(ascension*RAD_DEG) + "," + (declination*RAD_DEG);
1581         }
1582 
1583         /**
1584          * Return a string representation of this object with the right ascension
1585          * measured in hours, minutes, and seconds.
1586          * @hide draft / provisional / internal are hidden on Android
1587          */
1588         public String toHmsString() {
1589             return radToHms(ascension) + "," + radToDms(declination);
1590         }
1591 
1592         /**
1593          * The right ascension, in radians.
1594          * This is the position east or west along the equator
1595          * relative to the sun's position at the vernal equinox,
1596          * with positive angles representing East.
1597          * @hide draft / provisional / internal are hidden on Android
1598          */
1599         public final double ascension;
1600 
1601         /**
1602          * The declination, in radians.
1603          * This is the position north or south of the equatorial plane,
1604          * with positive angles representing north.
1605          * @hide draft / provisional / internal are hidden on Android
1606          */
1607         public final double declination;
1608     }
1609 
1610     /**
1611      * Represents the position of an  object in the sky relative to
1612      * the local horizon.
1613      * The <i>Altitude</i> represents the object's elevation above the horizon,
1614      * with objects below the horizon having a negative altitude.
1615      * The <i>Azimuth</i> is the geographic direction of the object from the
1616      * observer's position, with 0 representing north.  The azimuth increases
1617      * clockwise from north.
1618      * <p>
1619      * Note that Horizon objects are immutable and cannot be modified
1620      * once they are constructed.  This allows them to be passed and returned by
1621      * value without worrying about whether other code will modify them.
1622      *
1623      * @see CalendarAstronomer.Ecliptic
1624      * @see CalendarAstronomer.Equatorial
1625      * @hide Only a subset of ICU is exposed in Android
1626      * @hide draft / provisional / internal are hidden on Android
1627      */
1628     public static final class Horizon {
1629         /**
1630          * Constructs a Horizon coordinate object.
1631          * <p>
1632          * @param alt  The altitude, measured in radians above the horizon.
1633          * @param azim The azimuth, measured in radians clockwise from north.
1634          * @hide draft / provisional / internal are hidden on Android
1635          */
1636         public Horizon(double alt, double azim) {
1637             altitude = alt;
1638             azimuth = azim;
1639         }
1640 
1641         /**
1642          * Return a string representation of this object, with the
1643          * angles measured in degrees.
1644          * @hide draft / provisional / internal are hidden on Android
1645          */
1646         @Override
1647         public String toString() {
1648             return Double.toString(altitude*RAD_DEG) + "," + (azimuth*RAD_DEG);
1649         }
1650 
1651         /**
1652          * The object's altitude above the horizon, in radians.
1653          * @hide draft / provisional / internal are hidden on Android
1654          */
1655         public final double altitude;
1656 
1657         /**
1658          * The object's direction, in radians clockwise from north.
1659          * @hide draft / provisional / internal are hidden on Android
1660          */
1661         public final double azimuth;
1662     }
1663 
1664     static private String radToHms(double angle) {
1665         int hrs = (int) (angle*RAD_HOUR);
1666         int min = (int)((angle*RAD_HOUR - hrs) * 60);
1667         int sec = (int)((angle*RAD_HOUR - hrs - min/60.0) * 3600);
1668 
1669         return Integer.toString(hrs) + "h" + min + "m" + sec + "s";
1670     }
1671 
1672     static private String radToDms(double angle) {
1673         int deg = (int) (angle*RAD_DEG);
1674         int min = (int)((angle*RAD_DEG - deg) * 60);
1675         int sec = (int)((angle*RAD_DEG - deg - min/60.0) * 3600);
1676 
1677         return Integer.toString(deg) + "\u00b0" + min + "'" + sec + "\"";
1678     }
1679 }
1680