# Time 3, Exercise 2: two ways to decide which lunar years get a 13th month YEAR = 365.2422 MONTH = 29.530589 def run(leap_years): """offset after each year (lunar year end minus solar year end), in days.""" offset, offsets = 0.0, [] for year in range(1, len(leap_years) + 1): months = 13 if leap_years[year - 1] else 12 offset += months * MONTH - YEAR offsets.append(offset) return offsets def greedy_leaps(n): """Add a 13th month whenever twelve months would end more than half a month early.""" offset, leaps = 0.0, [] for _ in range(n): leap = offset + 12 * MONTH - YEAR < -MONTH / 2 leaps.append(leap) offset += (13 if leap else 12) * MONTH - YEAR return leaps pattern = {3, 6, 8, 11, 14, 17, 19} # a fixed 19-year pattern (as in the Hebrew calendar) fixed = [(y % 19 or 19) in pattern for y in range(1, 20)] greedy = greedy_leaps(19) for name, leaps in (("fixed pattern", fixed), ("greedy rule", greedy)): offsets = run(leaps) print(name, "| leap years:", [y for y, l in enumerate(leaps, 1) if l]) print(" range of offset:", round(min(offsets), 1), "to", round(max(offsets), 1), "days; after 19 years", round(offsets[-1], 2), "days") # Repeat each for 1000 years. fixed_1000 = [(y % 19 or 19) in pattern for y in range(1, 1001)] greedy_1000 = greedy_leaps(1000) for name, leaps in (("fixed pattern", fixed_1000), ("greedy rule", greedy_1000)): offsets = run(leaps) print(name, "after 1000 years: offset", round(offsets[-1], 2), "days; worst", round(max(abs(o) for o in offsets), 1), "days; leap years", sum(leaps)) # Output when run: # fixed pattern | leap years: [3, 6, 8, 11, 14, 17, 19] # range of offset: -26.3 to 1.6 days; after 19 years 0.09 days # greedy rule | leap years: [2, 5, 7, 10, 13, 15, 18] # range of offset: -14.0 to 14.1 days; after 19 years 0.09 days # fixed pattern after 1000 years: offset -7.88 days; worst 26.3 days; leap years 368 # greedy rule after 1000 years: offset -7.88 days; worst 14.8 days; leap years 368 # # Reading the output: both rules add 7 leap months in 19 years, and both end # the cycle only 0.09 of a day from the Sun. The fixed pattern lets the New Year # run as much as 26 days early before the leap months catch up; the greedy rule # keeps within about 14 days either way. The real calendars choose the leap # years so the lunar New Year stays within its own season, not to hug the Sun.