5D Library › 四柱排盘的历法计算与规则引擎 · English

第一章 儒略日与四柱的同余公式

一个不间断的日数

干支纪日从至迟春秋时代起连续不断,从未因改历而跳过或重复一天。儒略日(Julian Day Number)也是一个不间断的日数,从公元前 4713 年起逐日计数,同样不受历法改革的影响 (Reingold and Dershowitz 2018)。两个不间断的计数之间只差一个常数,所以日柱是儒略日的一个余数。

公历日期化为儒略日有一个只用整数运算的公式 (Fliegel and Van Flandern 1968):令 a=⌊(14−m)/12⌋a = \lfloor (14 – m)/12 \rfloor,y′=y+4800−ay' = y + 4800 – a,m′=m+12a−3m' = m + 12a – 3,则

JDN=d+⌊(153m′+2)/5⌋+365y′+⌊y′/4⌋−⌊y′/100⌋+⌊y′/400⌋−32045.\mathrm{JDN} = d + \lfloor (153m' + 2)/5 \rfloor + 365y' + \lfloor y'/4 \rfloor – \lfloor y'/100 \rfloor + \lfloor y'/400 \rfloor – 32045.

儒略历日期去掉两个世纪项、把常数换成 32083 即可。以甲子为 0,日柱的序号是 (JDN+49)mod⁡60(\mathrm{JDN} + 49) \bmod 60。

推导

# Chapter 1. Day pillars from the Julian Day Number.
# The Julian Day Number (JDN) counts days without a break across every
# calendar reform, from 1 January 4713 BCE (Julian calendar). For a
# Gregorian date (Fliegel and Van Flandern 1968):
#   a = (14 - m) // 12,  y' = y + 4800 - a,  m' = m + 12a - 3
#   JDN = d + (153m' + 2)//5 + 365y' + y'//4 - y'//100 + y'//400 - 32045
# The Julian-calendar version drops the two century terms and uses
# -32083. The sexagenary day cycle has also run without a break, so the
# day pillar is one residue: index = (JDN + 49) mod 60, 0 = jia-zi.
import datetime as dt

STEMS = ("jia", "yi", "bing", "ding", "wu", "ji", "geng", "xin", "ren",
         "gui")
BRANCHES = ("zi", "chou", "yin", "mao", "chen", "si", "wu", "wei", "shen",
            "you", "xu", "hai")

def jdn_gregorian(y, m, d):
    a = (14 - m) // 12
    yy, mm = y + 4800 - a, m + 12 * a - 3
    return (d + (153 * mm + 2) // 5 + 365 * yy + yy // 4 - yy // 100
            + yy // 400 - 32045)

def jdn_julian(y, m, d):
    a = (14 - m) // 12
    yy, mm = y + 4800 - a, m + 12 * a - 3
    return d + (153 * mm + 2) // 5 + 365 * yy + yy // 4 - 32083

def day_index(jdn):
    return (jdn + 49) % 60

def name(i):
    return STEMS[i % 10] + "-" + BRANCHES[i % 12]

if __name__ == "__main__":
    print("   JDN of 1 January 2000 = {:,d}".format(
        jdn_gregorian(2000, 1, 1)))
    anchors = (((2000, 1, 1), "wu-wu"), ((1949, 10, 1), "jia-zi"))
    for (y, m, d), want in anchors:
        i = day_index(jdn_gregorian(y, m, d))
        print("   {}-{:02d}-{:02d}: index {:2d} = {}  (published: {})".format(
            y, m, d, i, name(i), want))
    ok = all(jdn_gregorian(t.year, t.month, t.day) == t.toordinal()
             + 1721425 for t in (dt.date(1900, 1, 1) + dt.timedelta(days=k)
                                 for k in range(0, 73414)))
    print("   formula = Python ordinal + 1,721,425 on 1900-2100: {}".format(
        ok))
    a, b = jdn_julian(1582, 10, 4), jdn_gregorian(1582, 10, 15)
    print("   4 Oct 1582 (Julian) JDN {:,d} -> {};  15 Oct 1582 (Gregorian)"
          .format(a, name(day_index(a))))
    print("   JDN {:,d} -> {}: consecutive days, consecutive pillars".format(
        b, name(day_index(b))))
    crt = all(name(i) == STEMS[s] + "-" + BRANCHES[r] for i in range(60)
              for s, r in [(i % 10, i % 12)])
    pairs = {(i % 10, i % 12) for i in range(60)}
    print("   60 indices give 60 distinct stem-branch pairs: {};"
          .format(len(pairs) == 60 and crt))
    print("   stem and branch always share parity: {}".format(
        all((s - r) % 2 == 0 for s, r in pairs)))
    print("\nReading: the day pillar is a residue of an unbroken day count,")
    print("so it needs no table and survives the calendar reform of 1582.")
    print("Only the 60 pairs of stem and branch with equal parity occur.")
#    JDN of 1 January 2000 = 2,451,545
#    2000-01-01: index 54 = wu-wu  (published: wu-wu)
#    1949-10-01: index  0 = jia-zi  (published: jia-zi)
#    formula = Python ordinal + 1,721,425 on 1900-2100: True
#    4 Oct 1582 (Julian) JDN 2,299,160 -> gui-you;  15 Oct 1582 (Gregorian)
#    JDN 2,299,161 -> jia-xu: consecutive days, consecutive pillars
#    60 indices give 60 distinct stem-branch pairs: True;
#    stem and branch always share parity: True
#
# Reading: the day pillar is a residue of an unbroken day count,
# so it needs no table and survives the calendar reform of 1582.
# Only the 60 pairs of stem and branch with equal parity occur.

程序用两个公认的日柱核对常数:2000 年 1 月 1 日为戊午,1949 年 10 月 1 日为甲子。公式在 1900 年到 2100 年的每一天都与 Python 内部的日序数只差常数 1,721,425。1582 年 10 月 4 日(儒略历)的下一天是 10 月 15 日(格里历),两者的儒略日是相邻的 2,299,160 与 2,299,161,日柱是相邻的癸酉与甲戌:改历跳过了十天的日期,没有跳过任何一个干支。

一个容易被忽略的结构:天干有 10 个、地支有 12 个,它们配成的干支只有 60 个,而不是 120 个,因为干支同时前进,天干序号与地支序号的奇偶永远相同。由中国剩余定理,ℤ60\mathbb{Z}_{60} 恰好对应这些奇偶相同的配对。

五虎遁与五鼠遁

年柱以立春为界,第 37 本已经讨论过。月柱的天干由年干决定(五虎遁),时柱的天干由日干决定(五鼠遁)。两首歌诀都可以写成模 10 的仿射映射:以甲为 0、子为 0,寅月的天干是 (2×(年干mod⁡5)+2)mod⁡10(2 \times (\text{年干} \bmod 5) + 2) \bmod 10,此后每月加一;子时的天干是 2×(日干mod⁡5)mod⁡102 \times (\text{日干} \bmod 5) \bmod 10,此后每个时辰加一。

推导

# Chapter 1. Month and hour stems as affine maps (five tigers, five rats).
# Index stems 0-9 (jia ... gui) and branches 0-11 (zi ... hai).
# Month: the yin month (branch 2) of a year with stem Y has stem
#   (2 (Y mod 5) + 2) mod 10, and each later month adds one (the zi
#   and chou months close the year, after hai).
# Hour: the zi hour (branch 0) of a day with stem D has stem
#   2 (D mod 5) mod 10, and each later hour adds one.
# Both are checked against the rhyming tables as usually printed.
STEMS = ("jia", "yi", "bing", "ding", "wu", "ji", "geng", "xin", "ren",
         "gui")
BRANCHES = ("zi", "chou", "yin", "mao", "chen", "si", "wu", "wei", "shen",
            "you", "xu", "hai")
# five tigers: year stems -> stem of the yin month
TIGERS = {("jia", "ji"): "bing", ("yi", "geng"): "wu",
          ("bing", "xin"): "geng", ("ding", "ren"): "ren",
          ("wu", "gui"): "jia"}
# five rats: day stems -> stem of the zi hour
RATS = {("jia", "ji"): "jia", ("yi", "geng"): "bing",
        ("bing", "xin"): "wu", ("ding", "ren"): "geng",
        ("wu", "gui"): "ren"}

def month_stem(year_stem, branch):
    return (2 * (year_stem % 5) + 2 + (branch - 2) % 12) % 10

def hour_stem(day_stem, branch):
    return (2 * (day_stem % 5) + branch) % 10

if __name__ == "__main__":
    ok_t = all(STEMS[month_stem(STEMS.index(c), 2)] == v
               for k, v in TIGERS.items() for c in k)
    ok_r = all(STEMS[hour_stem(STEMS.index(c), 0)] == v
               for k, v in RATS.items() for c in k)
    print("   five tigers verse = (2 (Y mod 5) + 2) mod 10: {}".format(ok_t))
    print("   five rats verse   =  2 (D mod 5)      mod 10: {}".format(ok_r))
    hrs = [STEMS[hour_stem(0, b)] + "-" + BRANCHES[b] for b in range(12)]
    mos = [STEMS[month_stem(0, b)] + "-" + BRANCHES[b]
           for b in list(range(2, 12)) + [0, 1]]
    print("   hours of a jia day:")
    print("     " + " ".join(hrs[:6]))
    print("     " + " ".join(hrs[6:]))
    print("   months of a jia year, from the yin month:")
    print("     " + " ".join(mos[:6]))
    print("     " + " ".join(mos[6:]))
    par = all((month_stem(y, b) - b) % 2 == 0 and (hour_stem(y, b) - b) % 2
              == 0 for y in range(10) for b in range(12))
    print("   every month and hour pillar has stem and branch of equal")
    print("   parity: {}".format(par))
    n = 60 * 12 * 60 * 12
    print("   distinct charts: 60 years x 12 months x 60 days x 12 hours"
          " = {:,d}".format(n))
    print("\nReading: the month stem is fixed by the year stem and the")
    print("month, the hour stem by the day stem and the hour; the rhyming")
    print("tables are affine maps modulo 10. Of the eight characters only")
    print("four are free, giving 518,400 possible charts.")
#    five tigers verse = (2 (Y mod 5) + 2) mod 10: True
#    five rats verse   =  2 (D mod 5)      mod 10: True
#    hours of a jia day:
#      jia-zi yi-chou bing-yin ding-mao wu-chen ji-si
#      geng-wu xin-wei ren-shen gui-you jia-xu yi-hai
#    months of a jia year, from the yin month:
#      bing-yin ding-mao wu-chen ji-si geng-wu xin-wei
#      ren-shen gui-you jia-xu yi-hai bing-zi ding-chou
#    every month and hour pillar has stem and branch of equal
#    parity: True
#    distinct charts: 60 years x 12 months x 60 days x 12 hours = 518,400
#
# Reading: the month stem is fixed by the year stem and the
# month, the hour stem by the day stem and the hour; the rhyming
# tables are affine maps modulo 10. Of the eight characters only
# four are free, giving 518,400 possible charts.

程序把五虎遁「甲己之年丙作首……」与五鼠遁「甲己还加甲……」逐条与公式比较,全部相符,并列出甲年的十二个月柱与甲日的十二个时柱。月柱与时柱的天干地支奇偶也永远相同。由此可知,八个字中只有四个是自由的:年柱、月支、日柱、时支。可能的四柱组合共有 518,400 种,第五章将对它们全部计算。

注

年与月的边界不在这里。 本章的公式给出的是「某一月份、某一时辰」的干支;一个出生时刻落在哪一个月、哪一年,要看它在节气交节时刻的前后。节气时刻是天文计算,第三章与第六章再讨论。

小结

日柱是儒略日加 49 模 60 的余数,跨越 1582 年的改历仍然连续;五虎遁与五鼠遁是模 10 的仿射映射,与歌诀逐条相符。干支的奇偶约束使八个字中只有四个自由,全部可能的四柱共 518,400 种。

参考文献

Fliegel, Henry F., and Thomas C. Van Flandern. 1968. “A Machine Algorithm for Processing Calendar Dates.” Communications of the ACM 11 (10): 657.
Reingold, Edward M., and Nachum Dershowitz. 2018. Calendrical Calculations: The Ultimate Edition. 4th ed. Cambridge University Press.

Fan, Y. (2026). Four-Pillar Calendrical Computation and Formal Rule Engines: Julian-Day Sexagenary Cycles, Midnight-Boundary Disagreements, Birth-Time Sensitivity Bounds and Weighted-Graph Strength Scoring [四柱排盘的历法计算与规则引擎] (Version 1.0.0). 5D Library. https://doi.org/10.5281/zenodo.24090180 · Licensed under Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0).