<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><generator uri="https://jekyllrb.com/" version="4.4.1">Jekyll</generator><link href="https://cheems908.github.io/feed.xml" rel="self" type="application/atom+xml"/><link href="https://cheems908.github.io/" rel="alternate" type="text/html" hreflang="en"/><updated>2026-05-29T13:04:42+00:00</updated><id>https://cheems908.github.io/feed.xml</id><title type="html">Cheems908</title><subtitle>Y Zhang&apos;s personal academic website. </subtitle><entry><title type="html">概率论与数理统计 第4章 随机变量的数字特征</title><link href="https://cheems908.github.io/blog/2026/probability-chapter4-numerical-characteristics/" rel="alternate" type="text/html" title="概率论与数理统计 第4章 随机变量的数字特征"/><published>2026-05-29T10:00:00+00:00</published><updated>2026-05-29T10:00:00+00:00</updated><id>https://cheems908.github.io/blog/2026/probability-chapter4-numerical-characteristics</id><content type="html" xml:base="https://cheems908.github.io/blog/2026/probability-chapter4-numerical-characteristics/"><![CDATA[<h2 id="章节概览">章节概览</h2> <p>本章主要介绍随机变量的各种数字特征（Numerical Characteristics），包括：</p> <ul> <li><strong>4.1 随机变量的期望</strong> (Expectation of a Random Variable)</li> <li><strong>4.2 方差</strong> (Variance)</li> <li><strong>4.3 常见分布的数字特征</strong> (Characteristics of Common Distributions)</li> <li><strong>4.4 切比雪夫不等式</strong> (Chebyshev’s Inequality)</li> <li><strong>4.5 协方差与相关系数</strong> (Covariance and Correlation)</li> <li><strong>4.6 矩与协方差矩阵</strong> (Moments and Covariance Matrices)</li> </ul> <hr/> <h2 id="41-随机变量的期望-expectation-of-a-random-variable">4.1 随机变量的期望 (Expectation of a Random Variable)</h2> <h3 id="背景说明">背景说明</h3> <p>随机变量的分布函数（CDF）完整地描述了其统计规律性，但有时我们需要了解随机变量的某些特征值，如平均值或期望值，这些特征值可以让我们在不描述整个分布的情况下了解变量的中心位置。</p> <h3 id="411-离散型随机变量的期望">4.1.1 离散型随机变量的期望</h3> <p><strong>定义 4.1.1</strong> (Definition 4.1.1)</p> <p>设 \(X\) 是离散型随机变量，其概率分布律（PF, Probability Function）为：</p> \[P(X = x_k) = p_k, \quad k = 1, 2, \cdots\] <p>若级数 \(\sum_{k=1}^{\infty} x_k p_k\) 绝对收敛，则称 \(X\) 的<strong>期望</strong>（Expectation/Mean/Expected Value）存在，定义为：</p> \[E(X) = \sum_{k=1}^{\infty} x_k p_k\] <blockquote> <p><strong>注释</strong> (Remark)：不仅要求级数收敛，还要求<strong>绝对收敛</strong>（absolutely convergent），因为非绝对收敛的无穷级数重排后可能得到不同的和。绝对收敛保证了期望的唯一性。</p> </blockquote> <h3 id="412-连续型随机变量的期望">4.1.2 连续型随机变量的期望</h3> <p><strong>定义 4.1.2</strong> (Definition 4.1.2)</p> <p>设 \(X\) 是连续型随机变量，其概率密度函数（PDF, Probability Density Function）为 \(f(x)\)，若积分 \(\int_{-\infty}^{\infty} x f(x) dx\) 绝对收敛，则称 \(X\) 的期望存在，定义为：</p> \[E(X) = \int_{-\infty}^{\infty} x f(x) dx\] <h3 id="413-随机变量函数的期望">4.1.3 随机变量函数的期望</h3> <p><strong>定理 4.1.1</strong> (Theorem 4.1.1)</p> <p>设 \(X\) 是随机变量，\(Y = r(X)\) 是 \(X\) 的函数：</p> <p><strong>(1) 离散情形：</strong> 若 \(X\) 的分布律为 \(P(X = x_k) = p_k\)，且 \(\sum_{k=1}^{\infty} r(x_k) p_k\) 绝对收敛，则：</p> \[E(Y) = \sum_{k=1}^{\infty} r(x_k) p_k\] <p><strong>(2) 连续情形：</strong> 若 \(X\) 的密度函数为 \(f(x)\)，且 \(\int_{-\infty}^{\infty} r(x) f(x) dx\) 绝对收敛，则：</p> \[E(Y) = \int_{-\infty}^{\infty} r(x) f(x) dx\] <h3 id="414-多维随机变量函数的期望">4.1.4 多维随机变量函数的期望</h3> <p><strong>定理 4.1.2</strong> (Theorem 4.1.2)</p> <p>设 \(X_1, \cdots, X_n\) 是具有联合概率密度函数 \(f(x_1, \cdots, x_n)\) 的随机变量，\(Y = r(X_1, \cdots, X_n)\)，则：</p> \[E(Y) = \int_{-\infty}^{\infty} \cdots \int_{-\infty}^{\infty} r(x_1, \cdots, x_n) f(x_1, \cdots, x_n) dx_1 \cdots dx_n\] <h3 id="415-期望的性质">4.1.5 期望的性质</h3> <p><strong>定理 4.1.3</strong> (Theorem 4.1.3) - 线性性质</p> <p>若 \(Y = aX + b\)，其中 \(a, b\) 为有限常数，则：</p> \[E(Y) = aE(X) + b\] <blockquote> <p><strong>注释</strong>：一般情况下，\(E(XY) \neq E(X)E(Y)\)。</p> </blockquote> <p><strong>定理 4.1.4</strong> (Theorem 4.1.4) - 保序性</p> <ul> <li>若存在常数 \(a\) 使得 \(P(X \geq a) = 1\)，则 \(E(X) \geq a\)</li> <li>若存在常数 \(b\) 使得 \(P(X \leq b) = 1\)，则 \(E(X) \leq b\)</li> </ul> <p><strong>定理 4.1.5</strong> (Theorem 4.1.5) - 和的期望</p> <p>若 \(X_1, \cdots, X_n\) 是 \(n\) 个随机变量，且每个期望 \(E(X_i)\) 都存在 \((i = 1, \cdots, n)\)，则：</p> \[E(X_1 + \cdots + X_n) = E(X_1) + \cdots + E(X_n)\] <blockquote> <p><strong>注释</strong>：即使 \(X_1, \cdots, X_n\) 不独立，此性质也成立。</p> </blockquote> <p><strong>定理 4.1.6</strong> (Theorem 4.1.6) - 独立随机变量积的期望</p> <p>若 \(X_1, \cdots, X_n\) 是 \(n\) 个<strong>相互独立</strong>的随机变量，且每个期望 \(E(X_i)\) 都存在 \((i = 1, \cdots, n)\)，则：</p> \[E(X_1 X_2 \cdots X_n) = E(X_1) \times E(X_2) \times \cdots \times E(X_n)\] <hr/> <h2 id="42-方差-variance">4.2 方差 (Variance)</h2> <h3 id="421-方差的定义">4.2.1 方差的定义</h3> <p><strong>定义 4.2.1</strong> (Definition 4.2.1)</p> <p>设 \(X\) 是具有有限均值 \(\mu = E(X)\) 的随机变量，\(X\) 的<strong>方差</strong>（Variance）定义为：</p> \[\sigma_X^2 = \text{Var}(X) = E[(X - \mu)^2]\] <ul> <li>若 \(X\) 的均值无穷大或不存在，则称 \(\text{Var}(X)\) 不存在</li> <li><strong>标准差</strong>（Standard Deviation）\(\sigma_X\) 是方差的非负平方根</li> </ul> <p><strong>方差的意义</strong>：方差描述了随机变量取值与其期望之间的偏离程度。取值越集中，方差越小；取值越分散，方差越大。方差是衡量随机变量<strong>离散程度</strong>的指标。</p> <h3 id="422-方差的计算公式">4.2.2 方差的计算公式</h3> <p><strong>定理 4.2.1</strong> (Theorem 4.2.1)</p> <p>对任意随机变量 \(X\)：</p> \[\text{Var}(X) = E(X^2) - [E(X)]^2\] <h3 id="423-方差的性质">4.2.3 方差的性质</h3> <p><strong>定理 4.2.2</strong> (Theorem 4.2.2)</p> <p>对每个随机变量 \(X\)，\(\text{Var}(X) \geq 0\)。若 \(X\) 是有界随机变量，则 \(\text{Var}(X)\) 必定存在且有限。</p> <p><strong>定理 4.2.3</strong> (Theorem 4.2.3)</p> <p>\(\text{Var}(X) = 0\) 当且仅当存在常数 \(c = E(X)\) 使得 \(P(X = c) = 1\)。</p> <p><strong>定理 4.2.4</strong> (Theorem 4.2.4) - 方差的展开</p> <p>若 \(X\) 和 \(Y\) 是满足 \(\text{Var}(X) &lt; \infty\) 和 \(\text{Var}(Y) &lt; \infty\) 的随机变量，\(a, b, c\) 为常数，则：</p> \[\text{Var}(X + Y) = \text{Var}(X) + \text{Var}(Y) + 2[E(XY) - E(X)E(Y)]\] \[\text{Var}(aX + bY + c) = a^2\text{Var}(X) + b^2\text{Var}(Y) + 2ab[E(XY) - E(X)E(Y)]\] <p><strong>定理 4.2.5</strong> (Theorem 4.2.5) - 独立随机变量线性组合的方差</p> <p>若 \(X_1, \cdots, X_n\) 是具有有限均值的独立随机变量，\(a_1, \cdots, a_n\) 和 \(b\) 是任意常数，则：</p> \[\text{Var}(a_1 X_1 + \cdots + a_n X_n + b) = a_1^2 \text{Var}(X_1) + \cdots + a_n^2 \text{Var}(X_n)\] <hr/> <h2 id="43-常见分布的数字特征-characteristics-of-common-distributions">4.3 常见分布的数字特征 (Characteristics of Common Distributions)</h2> <h3 id="431-伯努利分布-bernoulli-distribution">4.3.1 伯努利分布 (Bernoulli Distribution)</h3> <p><strong>定理 4.3.1</strong> (Theorem 4.3.1)</p> <p>若随机变量 \(X\) 服从参数为 \(p\) \((0 \leq p \leq 1)\) 的伯努利分布，即 \(X\) 只能取 0 和 1，且：</p> \[P(X = 1) = p, \quad P(X = 0) = 1 - p\] <p>则：</p> \[E(X) = p, \quad \text{Var}(X) = p(1-p)\] <p><strong>伯努利试验</strong> (Bernoulli Trials)：若有限或无限序列 \(X_1, X_2, \cdots\) 中的随机变量相互独立同分布（IID），且每个 \(X_i\) 服从参数为 \(p\) 的伯努利分布，则称 \(X_1, X_2, \cdots\) 为参数为 \(p\) 的伯努利试验。</p> <h3 id="432-二项分布-binomial-distribution">4.3.2 二项分布 (Binomial Distribution)</h3> <p><strong>定理 4.3.2</strong> (Theorem 4.3.2)</p> <p>若随机变量 \(X_1, \cdots, X_n\) 构成 \(n\) 次参数为 \(p\) 的伯努利试验，且 \(X = X_1 + \cdots + X_n\)，则 \(X\) 服从参数为 \(n\) 和 \(p\) 的二项分布 \(B(n, p)\)，其分布律为：</p> \[P(X = k) = \binom{n}{k} p^k (1-p)^{n-k}, \quad k = 0, 1, \cdots, n\] <p>则：</p> \[E(X) = np, \quad \text{Var}(X) = np(1-p)\] <h3 id="433-泊松分布-poisson-distribution">4.3.3 泊松分布 (Poisson Distribution)</h3> <p><strong>定理 4.3.3</strong> (Theorem 4.3.3)</p> <p>若 \(X \sim \text{Poisson}(\lambda)\)，则：</p> \[E(X) = \text{Var}(X) = \lambda\] <p>分布律为：</p> \[P(X = k) = \frac{\lambda^k e^{-\lambda}}{k!}, \quad k = 0, 1, 2, \cdots\] <h3 id="434-超几何分布-hypergeometric-distribution">4.3.4 超几何分布 (Hypergeometric Distribution)</h3> <p><strong>定理 4.3.4</strong> (Theorem 4.3.4)</p> <p>设 \(X \sim H(N, m, n)\)，其中参数 \(N, m, n\) 均为正数，则：</p> \[E(X) = \frac{nm}{N}\] \[\text{Var}(X) = \frac{nm(N-m)(N-n)}{N^2(N-1)}\] <h3 id="435-负二项分布-negative-binomial-distribution">4.3.5 负二项分布 (Negative Binomial Distribution)</h3> <p><strong>定理 4.3.5</strong> (Theorem 4.3.5)</p> <p>若 \(X\) 服从参数为 \(r\) 和 \(p\) 的负二项分布，则：</p> \[E(X) = \frac{r}{p}, \quad \text{Var}(X) = \frac{r(1-p)}{p^2}\] <h3 id="436-均匀分布-uniform-distribution">4.3.6 均匀分布 (Uniform Distribution)</h3> <p><strong>定理 4.3.6</strong> (Theorem 4.3.6)</p> <p>设 \(X \sim U[a, b]\)，则：</p> \[E(X) = \frac{a+b}{2}, \quad \text{Var}(X) = \frac{(b-a)^2}{12}\] <p>概率密度函数为：</p> \[f(x) = \begin{cases} \frac{1}{b-a}, &amp; a \leq x \leq b \\ 0, &amp; \text{其他} \end{cases}\] <h3 id="437-指数分布-exponential-distribution">4.3.7 指数分布 (Exponential Distribution)</h3> <p><strong>定理 4.3.7</strong> (Theorem 4.3.7)</p> <p>设 \(X \sim \text{Exp}(\lambda)\)，则：</p> \[E(X) = \frac{1}{\lambda}, \quad \text{Var}(X) = \frac{1}{\lambda^2}\] <p>概率密度函数为：</p> \[f(x) = \begin{cases} \lambda e^{-\lambda x}, &amp; x &gt; 0 \\ 0, &amp; x \leq 0 \end{cases}\] <h3 id="438-正态分布-normal-distribution">4.3.8 正态分布 (Normal Distribution)</h3> <p><strong>定理 4.3.8</strong> (Theorem 4.3.8)</p> <p>设 \(X \sim N(\mu, \sigma^2)\)，则：</p> \[E(X) = \mu, \quad \text{Var}(X) = \sigma^2\] <p>概率密度函数为：</p> \[f(x) = \frac{1}{\sqrt{2\pi}\sigma} e^{-\frac{(x-\mu)^2}{2\sigma^2}}, \quad -\infty &lt; x &lt; \infty\] <p>其中 \(-\infty &lt; \mu &lt; \infty\) 和 \(\sigma &gt; 0\) 是两个参数。</p> <p><strong>标准化</strong>：令 \(Y = \frac{X - \mu}{\sigma}\)，则 \(Y \sim N(0, 1)\)（标准正态分布）。</p> <blockquote> <p><strong>重要说明</strong>：正态分布的两个参数恰好是其均值和方差，正态分布完全由其均值和方差确定。</p> </blockquote> <h3 id="439-gamma分布-gamma-distribution">4.3.9 Gamma分布 (Gamma Distribution)</h3> <p><strong>定理 4.3.9</strong> (Theorem 4.3.9)</p> <p>设 \(X \sim \text{Gamma}(\alpha, \beta)\)，则：</p> \[E(X) = \alpha\beta, \quad \text{Var}(X) = \alpha\beta^2\] <p><strong>备注 4.3.1</strong> (Remark 4.3.1)</p> <p>特别地，当 \(\alpha = \frac{n}{2}\)，\(\beta = 2\) 时，Gamma分布退化为自由度为 \(n\) 的 <strong>卡方分布</strong>（Chi-squared Distribution）\(\chi^2(n)\)：</p> <ul> <li>若 \(X \sim \chi^2(n)\)，则 \(E(X) = n\)，\(\text{Var}(X) = 2n\)</li> </ul> <hr/> <h2 id="44-切比雪夫不等式-chebyshevs-inequality">4.4 切比雪夫不等式 (Chebyshev’s Inequality)</h2> <h3 id="441-切比雪夫不等式">4.4.1 切比雪夫不等式</h3> <p><strong>定理 4.4.1</strong> (Theorem 4.4.1)</p> <p>设 \(X\) 是具有均值 \(E(X)\) 和方差 \(\text{Var}(X) = \sigma^2\) 的随机变量，则对任意 \(\varepsilon &gt; 0\)：</p> \[P(|X - E(X)| \geq \varepsilon) \leq \frac{\text{Var}(X)}{\varepsilon^2} = \frac{\sigma^2}{\varepsilon^2}\] <p><strong>等价形式</strong>：</p> \[P(|X - E(X)| &lt; \varepsilon) \geq 1 - \frac{\text{Var}(X)}{\varepsilon^2}\] <p>或令 \(k = \frac{\varepsilon}{\sigma}\)：</p> \[P(|X - E(X)| \geq k\sigma) \leq \frac{1}{k^2}\] <h3 id="442-证明思路">4.4.2 证明思路</h3> <p><strong>注释 4.4.1</strong> (Remark 4.4.1)</p> <p>切比雪夫不等式提供了一种在不知道 \(X\) 具体分布的情况下近似概率的方法。</p> <p><strong>注释 4.4.2</strong> (Remark 4.4.2)</p> <p>由于切比雪夫不等式不对分布形状做任何假设，这是一个缺点。虽然不等式成立，但它过于一般化，实用性有限，因此主要用于理论研究。切比雪夫的结果虽然正确，但与实际值相比非常保守。</p> <hr/> <h2 id="45-协方差与相关系数-covariance-and-correlation">4.5 协方差与相关系数 (Covariance and Correlation)</h2> <h3 id="451-协方差的定义">4.5.1 协方差的定义</h3> <p><strong>定义 4.5.1</strong> (Definition 4.5.1)</p> <p>设 \(X\) 和 \(Y\) 是具有有限均值的随机变量，\(E(X) = \mu_X\)，\(E(Y) = \mu_Y\)。\(X\) 和 \(Y\) 的<strong>协方差</strong>（Covariance）定义为：</p> \[\text{Cov}(X, Y) = E[(X - \mu_X)(Y - \mu_Y)] = E(XY) - E(X)E(Y)\] <p>特别地，当 \(X = Y\) 时，\(\text{Cov}(X, X) = \text{Var}(X)\)。</p> <p><strong>协方差的意义</strong>：协方差是衡量两个随机变量之间关联性质的指标，它只描述两个随机变量之间的<strong>线性关系</strong>。</p> <h3 id="452-协方差与方差的关系">4.5.2 协方差与方差的关系</h3> <p><strong>定理 4.5.1</strong> (Theorem 4.5.1)</p> <p>若 \(X\) 和 \(Y\) 是满足 \(\text{Var}(X) &lt; \infty\) 和 \(\text{Var}(Y) &lt; \infty\) 的随机变量，\(a, b, c\) 为常数，则：</p> \[\text{Var}(X + Y) = \text{Var}(X) + \text{Var}(Y) + 2\text{Cov}(X, Y)\] \[\text{Var}(aX + bY + c) = a^2\text{Var}(X) + b^2\text{Var}(Y) + 2ab\text{Cov}(X, Y)\] <h3 id="453-协方差的性质">4.5.3 协方差的性质</h3> <p><strong>命题 4.5.1</strong> (Proposition 4.5.1)</p> <p>协方差具有以下性质：对随机变量 \(X, Y, Z\) 和常数 \(a, b\)：</p> <ol> <li><strong>对称性</strong>：\(\text{Cov}(X, Y) = \text{Cov}(Y, X)\)</li> <li><strong>齐次性</strong>：\(\text{Cov}(aX, bY) = ab\text{Cov}(X, Y)\)</li> <li><strong>可加性</strong>：\(\text{Cov}(X + Y, Z) = \text{Cov}(X, Z) + \text{Cov}(Y, Z)\)</li> </ol> <h3 id="454-相关系数的定义">4.5.4 相关系数的定义</h3> <p><strong>定义 4.5.2</strong> (Definition 4.5.2)</p> <p>设 \(X\) 和 \(Y\) 是具有有限方差 \(\sigma_X^2\) 和 \(\sigma_Y^2\) 的随机变量，则 \(X\) 和 \(Y\) 的<strong>相关系数</strong>（Correlation Coefficient）定义为：</p> \[\rho_{X,Y} = \frac{\text{Cov}(X, Y)}{\sigma_X \sigma_Y} = \frac{\text{Cov}(X, Y)}{\sqrt{\text{Var}(X)}\sqrt{\text{Var}(Y)}}\] <p><strong>备注 4.5.1</strong> (Remark 4.5.1)</p> <p>令 \(X^* = \frac{X - \mu_X}{\sigma_X}\)，\(Y^* = \frac{Y - \mu_Y}{\sigma_Y}\)，则 \(E(X^*) = E(Y^*) = 0\)，\(\text{Var}(X^*) = \text{Var}(Y^*) = 1\)，\(X^*\) 和 \(Y^*\) 分别称为 \(X\) 和 \(Y\) 的<strong>标准化变量</strong>（Standardized Variables）。</p> \[\rho_{X,Y} = \text{Cov}(X^*, Y^*)\] <p>\(\rho_{X,Y}\) 是无量纲的（free of units）。</p> <h3 id="455-相关系数的性质">4.5.5 相关系数的性质</h3> <p><strong>定理 4.5.2</strong> (Theorem 4.5.2)</p> <p>相关系数具有以下性质：</p> <ol> <li> \[-1 \leq \rho_{X,Y} \leq 1\] </li> <li> <table> <tbody> <tr> <td>$$</td> <td>\rho_{X,Y}</td> <td>= 1\(当且仅当存在常数\)a, b\(使得\)P(Y = a + bX) = 1$$，且：</td> </tr> </tbody> </table> <ul> <li>当 \(b &gt; 0\) 时，\(\rho_{X,Y} = 1\)</li> <li>当 \(b &lt; 0\) 时，\(\rho_{X,Y} = -1\)</li> </ul> </li> </ol> <p><strong>解释</strong>：</p> <ul> <li>相关系数接近 1 表示 \(X\) 和 \(Y\) 通常同时取大值或小值</li> <li>相关系数接近 -1 表示 \(X\) 取大值时 \(Y\) 取小值（反之亦然）</li> </ul> <h3 id="456-相关性的分类">4.5.6 相关性的分类</h3> <p><strong>定义 4.5.3</strong> (Definition 4.5.3)</p> <ul> <li>若 \(\text{Cov}(X, Y) &gt; 0\)，称 \(X\) 和 \(Y\) <strong>正相关</strong>（Positive Correlated）</li> <li>若 \(\text{Cov}(X, Y) &lt; 0\)，称 \(X\) 和 \(Y\) <strong>负相关</strong>（Negative Correlated）</li> <li>若 \(\text{Cov}(X, Y) = 0\)，称 \(X\) 和 \(Y\) <strong>不相关</strong>（Uncorrelated）</li> </ul> <h3 id="457-独立性与相关性的关系">4.5.7 独立性与相关性的关系</h3> <p><strong>备注 4.5.2</strong> (Remark 4.5.2)</p> <ul> <li>若 \(X\) 和 \(Y\) 不相关，意味着 \(X\) 和 \(Y\) 之间没有线性关系，但可能存在其他关系</li> <li>由定理 4.1.6，若 \(X\) 和 \(Y\) 独立，则 \(E(XY) = E(X)E(Y)\)，\(\text{Cov}(X, Y) = 0\)</li> <li>即：<strong>独立性蕴含不相关性</strong></li> <li>等价地，若 \(\text{Cov}(X, Y) \neq 0\) 或 \(\rho_{X,Y} \neq 0\)，则 \(X\) 和 \(Y\) 不独立</li> <li>然而，若 \(X\) 和 \(Y\) 不相关，它们可能是依赖的也可能是独立的</li> <li><strong>不相关的随机变量不一定独立！</strong></li> </ul> <h3 id="458-二元正态分布的相关性">4.5.8 二元正态分布的相关性</h3> <p><strong>命题 4.5.3</strong> (Proposition 4.5.3)</p> <p>设 \((X, Y)\) 服从二元正态分布 \(N(\mu_1, \mu_2, \sigma_1^2, \sigma_2^2, \rho)\)，则参数 \(\rho\) 恰好是 \(X\) 和 \(Y\) 的相关系数。</p> <p><strong>重要性质</strong>：设 \((X, Y)\) 服从二元正态分布，则 \(X\) 和 \(Y\) 独立当且仅当它们不相关（即 \(\rho = 0\)）。</p> <hr/> <h2 id="46-矩与协方差矩阵-moments-and-covariance-matrices">4.6 矩与协方差矩阵 (Moments and Covariance Matrices)</h2> <h3 id="461-矩的定义">4.6.1 矩的定义</h3> <p><strong>定义 4.6.1</strong> (Definition 4.6.1)</p> <p>设 \(X\) 是随机变量，且 \(E(X^k)\) 存在，\(k = 1, 2, \cdots\)：</p> <ul> <li>\(E(X^k)\) 称为 \(X\) 的 <strong>\(k\) 阶原点矩</strong>（\(k\)-th Moment about the Origin）</li> <li>\(E\{[X - E(X)]^k\}\)（\(k = 2, 3, \cdots\)）若存在，称为 \(X\) 的 <strong>\(k\) 阶中心矩</strong>（\(k\)-th Central Moment）</li> <li>\(E\{[X - E(X)]^k [Y - E(Y)]^l\}\)（\(k, l = 1, 2, \cdots\)）若存在，称为 \(X\) 和 \(Y\) 的 <strong>\(k+l\) 阶混合中心矩</strong>（Mixed Central Moment of Order \(k+l\)）</li> </ul> <p><strong>重要说明</strong>：</p> <ul> <li>均值 \(E(X)\) 是 \(X\) 的一阶原点矩</li> <li>方差 \(\text{Var}(X)\) 是 \(X\) 的二阶中心矩</li> <li>协方差 \(\text{Cov}(X, Y)\) 是 \(X\) 和 \(Y\) 的二元二阶混合中心矩</li> </ul> <h3 id="462-协方差矩阵的定义">4.6.2 协方差矩阵的定义</h3> <p><strong>定义 4.6.2</strong> (Definition 4.6.2)</p> <p>设 \((X_1, X_2)\) 的二阶中心矩存在，记为：</p> \[c_{11} = \text{Var}(X_1), \quad c_{22} = \text{Var}(X_2), \quad c_{12} = c_{21} = \text{Cov}(X_1, X_2)\] <p>则矩阵：</p> \[C = \begin{pmatrix} c_{11} &amp; c_{12} \\ c_{21} &amp; c_{22} \end{pmatrix}\] <p>定义为 \((X_1, X_2)\) 的<strong>协方差矩阵</strong>（Covariance Matrix）。</p> <p><strong>推广到 \(n\) 维</strong>：</p> <p>\((X_1, X_2, \cdots, X_n)\) 的协方差矩阵定义为：</p> \[C = \begin{pmatrix} c_{11} &amp; c_{12} &amp; \cdots &amp; c_{1n} \\ c_{21} &amp; c_{22} &amp; \cdots &amp; c_{2n} \\ \vdots &amp; \vdots &amp; \ddots &amp; \vdots \\ c_{n1} &amp; c_{n2} &amp; \cdots &amp; c_{nn} \end{pmatrix}\] <p>其中 \(c_{ij} = \text{Cov}(X_i, X_j)\)，\(i, j = 1, 2, \cdots, n\)。</p> <p>由于 \(c_{ij} = c_{ji}\)（\(i \neq j\)），协方差矩阵是<strong>对称矩阵</strong>（Symmetric Matrix）。</p> <h3 id="463-二元正态分布的协方差矩阵表示">4.6.3 二元正态分布的协方差矩阵表示</h3> <p>设 \((X_1, X_2) \sim N(\mu_1, \mu_2, \sigma_1^2, \sigma_2^2, \rho)\)，则协方差矩阵为：</p> \[C = \begin{pmatrix} \sigma_1^2 &amp; \rho\sigma_1\sigma_2 \\ \rho\sigma_1\sigma_2 &amp; \sigma_2^2 \end{pmatrix}\] <h3 id="464-非退化情况的概率密度函数">4.6.4 非退化情况的概率密度函数</h3> <table> <tbody> <tr> <td>若 $$</td> <td>C</td> <td>\neq 0\(，则\)C\(的逆矩阵存在，\)(X, Y)\(称为**非退化的**（Non-degenerate）。若\)</td> <td>C</td> <td>= 0\(，\)(X, Y)$$ 是<strong>退化的</strong>（Degenerate），没有密度函数。</td> </tr> </tbody> </table> <p>对于非退化情况，\((X_1, X_2)\) 的概率密度函数为：</p> \[f(x_1, x_2) = \frac{1}{2\pi|C|^{1/2}} \exp\left\{-\frac{1}{2}(X - \mu)^T C^{-1} (X - \mu)\right\}\] <table> <tbody> <tr> <td>其中 \(X = \begin{pmatrix} x_1 \\ x_2 \end{pmatrix}\)，\(\mu = \begin{pmatrix} \mu_1 \\ \mu_2 \end{pmatrix}\)，$$</td> <td>C</td> <td>\(和\)C^{-1}\(分别是\)C\(的行列式和逆矩阵，\)(X - \mu)^T\(是\)(X - \mu)$$ 的转置。</td> </tr> </tbody> </table> <h3 id="465-n-维正态分布">4.6.5 \(n\) 维正态分布</h3> <p>上述结果可推广到 \(n\) 维正态随机向量 \((X_1, X_2, \cdots, X_n)\)，概率密度函数为：</p> \[f(x_1, \cdots, x_n) = \frac{1}{(2\pi)^{n/2}|C|^{1/2}} \exp\left\{-\frac{1}{2}(X - \mu)^T C^{-1} (X - \mu)\right\}\] <h3 id="466-n-维正态分布的性质">4.6.6 \(n\) 维正态分布的性质</h3> <p>\(n\) 维正态随机向量 \((X_1, \cdots, X_n)\) 具有以下性质：</p> <ol> <li> <p><strong>边缘分布</strong>：给定 \(n\) 维正态随机向量 \((X_1, \cdots, X_n)\)，其所有分量 \(X_i\)（\(i = 1, \cdots, n\)）都是正态随机变量；反之，若 \(X_i\)（\(i = 1, \cdots, n\)）是相互独立的正态随机变量，则 \((X_1, \cdots, X_n)\) 是 \(n\) 维正态随机向量。</p> </li> <li> <p><strong>线性组合</strong>：\((X_1, \cdots, X_n)\) 服从 \(n\) 维正态分布当且仅当其任意线性组合 \(a_1 X_1 + \cdots + a_n X_n\) 服从正态分布（\(a_1, \cdots, a_n\) 不全为零）。</p> </li> <li> <p><strong>线性变换的不变性</strong>：若 \((X_1, \cdots, X_n)\) 服从 \(n\) 维正态分布，\(Y_1, Y_2, \cdots, Y_m\) 是 \(X_i\)（\(i = 1, \cdots, n\)）的线性函数（系数不全为零），则 \((Y_1, Y_2, \cdots, Y_m)\) 服从 \(m\) 维正态分布。</p> <blockquote> <p><strong>注释</strong>：这表明正态分布在线性变换下保持不变。上述 \(m\) 维正态分布可能是退化的，没有密度函数。</p> </blockquote> </li> <li> <p><strong>独立性与不相关性等价</strong>：若 \((X_1, \cdots, X_n)\) 服从 \(n\) 维正态分布，则 \(X_1, \cdots, X_n\) 相互独立当且仅当它们两两不相关。</p> </li> </ol> <h3 id="467-正态随机向量的线性变换">4.6.7 正态随机向量的线性变换</h3> <p><strong>定理 4.6.2</strong> (Theorem 4.6.2)</p> <p>若 \((X_1, X_2) \sim N(\mu_1, \mu_2, \sigma_1^2, \sigma_2^2, \rho)\)，则：</p> \[aX_1 + bX_2 \sim N(a\mu_1 + b\mu_2, a^2\sigma_1^2 + b^2\sigma_2^2 + 2ab\rho\sigma_1\sigma_2)\] <hr/> <h2 id="关键术语中英对照表">关键术语中英对照表</h2> <table> <thead> <tr> <th>中文</th> <th>英文</th> </tr> </thead> <tbody> <tr> <td>期望/均值</td> <td>Expectation/Mean/Expected Value</td> </tr> <tr> <td>方差</td> <td>Variance</td> </tr> <tr> <td>标准差</td> <td>Standard Deviation</td> </tr> <tr> <td>概率分布律</td> <td>Probability Function (PF)</td> </tr> <tr> <td>概率密度函数</td> <td>Probability Density Function (PDF)</td> </tr> <tr> <td>累积分布函数</td> <td>Cumulative Distribution Function (CDF)</td> </tr> <tr> <td>伯努利分布</td> <td>Bernoulli Distribution</td> </tr> <tr> <td>二项分布</td> <td>Binomial Distribution</td> </tr> <tr> <td>泊松分布</td> <td>Poisson Distribution</td> </tr> <tr> <td>超几何分布</td> <td>Hypergeometric Distribution</td> </tr> <tr> <td>负二项分布</td> <td>Negative Binomial Distribution</td> </tr> <tr> <td>均匀分布</td> <td>Uniform Distribution</td> </tr> <tr> <td>指数分布</td> <td>Exponential Distribution</td> </tr> <tr> <td>正态分布/高斯分布</td> <td>Normal/Gaussian Distribution</td> </tr> <tr> <td>Gamma分布</td> <td>Gamma Distribution</td> </tr> <tr> <td>卡方分布</td> <td>Chi-squared Distribution</td> </tr> <tr> <td>切比雪夫不等式</td> <td>Chebyshev’s Inequality</td> </tr> <tr> <td>协方差</td> <td>Covariance</td> </tr> <tr> <td>相关系数</td> <td>Correlation Coefficient</td> </tr> <tr> <td>正相关</td> <td>Positive Correlated</td> </tr> <tr> <td>负相关</td> <td>Negative Correlated</td> </tr> <tr> <td>不相关</td> <td>Uncorrelated</td> </tr> <tr> <td>独立</td> <td>Independent</td> </tr> <tr> <td>矩</td> <td>Moment</td> </tr> <tr> <td>原点矩</td> <td>Moment about the Origin</td> </tr> <tr> <td>中心矩</td> <td>Central Moment</td> </tr> <tr> <td>混合矩</td> <td>Mixed Moment</td> </tr> <tr> <td>协方差矩阵</td> <td>Covariance Matrix</td> </tr> <tr> <td>对称矩阵</td> <td>Symmetric Matrix</td> </tr> <tr> <td>退化/非退化</td> <td>Degenerate/Non-degenerate</td> </tr> <tr> <td>标准化变量</td> <td>Standardized Variables</td> </tr> <tr> <td>二元正态分布</td> <td>Bivariate Normal Distribution</td> </tr> <tr> <td>\(n\) 维正态分布</td> <td>\(n\)-dimensional Normal Distribution</td> </tr> <tr> <td>线性变换</td> <td>Linear Transformation</td> </tr> <tr> <td>独立同分布</td> <td>Independent and Identically Distributed (IID)</td> </tr> </tbody> </table>]]></content><author><name></name></author><category term="mathematics"/><category term="probability"/><category term="statistics"/><category term="math"/><summary type="html"><![CDATA[概率论与数理统计第4章学习笔记，涵盖期望、方差、常见分布的数字特征、切比雪夫不等式、协方差与相关系数、矩与协方差矩阵等内容。]]></summary></entry><entry><title type="html">a post with plotly.js</title><link href="https://cheems908.github.io/blog/2025/plotly/" rel="alternate" type="text/html" title="a post with plotly.js"/><published>2025-03-26T14:24:00+00:00</published><updated>2025-03-26T14:24:00+00:00</updated><id>https://cheems908.github.io/blog/2025/plotly</id><content type="html" xml:base="https://cheems908.github.io/blog/2025/plotly/"><![CDATA[<p>This is an example post with some <a href="https://plotly.com/javascript/">plotly</a> code.</p> <div class="language-markdown highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">```</span><span class="nl">plotly
</span><span class="sb">{
  "data": [
    {
      "x": [1, 2, 3, 4],
      "y": [10, 15, 13, 17],
      "type": "scatter"
    },
    {
      "x": [1, 2, 3, 4],
      "y": [16, 5, 11, 9],
      "type": "scatter"
    }
  ]
}</span>
<span class="p">```</span>
</code></pre></div></div> <p>Which generates:</p> <pre><code class="language-plotly">{
  "data": [
    {
      "x": [1, 2, 3, 4],
      "y": [10, 15, 13, 17],
      "type": "scatter"
    },
    {
      "x": [1, 2, 3, 4],
      "y": [16, 5, 11, 9],
      "type": "scatter"
    }
  ]
}
</code></pre> <p>Also another example chart.</p> <div class="language-markdown highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">```</span><span class="nl">plotly
</span><span class="sb">{
  "data": [
    {
      "x": [1, 2, 3, 4],
      "y": [10, 15, 13, 17],
      "mode": "markers"
    },
    {
      "x": [2, 3, 4, 5],
      "y": [16, 5, 11, 9],
      "mode": "lines"
    },
    {
      "x": [1, 2, 3, 4],
      "y": [12, 9, 15, 12],
      "mode": "lines+markers"
    }
  ],
  "layout": {
    "title": {
      "text": "Line and Scatter Plot"
    }
  }
}</span>
<span class="p">```</span>
</code></pre></div></div> <p>This is how it looks like:</p> <pre><code class="language-plotly">{
  "data": [
    {
      "x": [1, 2, 3, 4],
      "y": [10, 15, 13, 17],
      "mode": "markers"
    },
    {
      "x": [2, 3, 4, 5],
      "y": [16, 5, 11, 9],
      "mode": "lines"
    },
    {
      "x": [1, 2, 3, 4],
      "y": [12, 9, 15, 12],
      "mode": "lines+markers"
    }
  ],
  "layout": {
    "title": {
      "text": "Line and Scatter Plot"
    }
  }
}
</code></pre>]]></content><author><name></name></author><category term="sample-posts"/><category term="formatting"/><category term="charts"/><summary type="html"><![CDATA[this is what included plotly.js code could look like]]></summary></entry><entry><title type="html">a post with image galleries</title><link href="https://cheems908.github.io/blog/2024/photo-gallery/" rel="alternate" type="text/html" title="a post with image galleries"/><published>2024-12-04T01:59:00+00:00</published><updated>2024-12-04T01:59:00+00:00</updated><id>https://cheems908.github.io/blog/2024/photo-gallery</id><content type="html" xml:base="https://cheems908.github.io/blog/2024/photo-gallery/"><![CDATA[<p>The images in this post are all zoomable, arranged into different mini-galleries using different libraries.</p> <h2 id="lightbox2"><a href="https://lokeshdhakar.com/projects/lightbox2/">Lightbox2</a></h2> <p><a href="https://cdn.photoswipe.com/photoswipe-demo-images/photos/1/img-2500.jpg" data-lightbox="roadtrip"><img src="https://cdn.photoswipe.com/photoswipe-demo-images/photos/1/img-200.jpg"/></a> <a href="https://cdn.photoswipe.com/photoswipe-demo-images/photos/2/img-2500.jpg" data-lightbox="roadtrip"><img src="https://cdn.photoswipe.com/photoswipe-demo-images/photos/2/img-200.jpg"/></a> <a href="https://cdn.photoswipe.com/photoswipe-demo-images/photos/3/img-2500.jpg" data-lightbox="roadtrip"><img src="https://cdn.photoswipe.com/photoswipe-demo-images/photos/3/img-200.jpg"/></a></p> <hr/> <h2 id="photoswipe"><a href="https://photoswipe.com/">PhotoSwipe</a></h2> <div class="pswp-gallery pswp-gallery--single-column" id="gallery--getting-started"> <a href="https://cdn.photoswipe.com/photoswipe-demo-images/photos/2/img-2500.jpg" data-pswp-width="1669" data-pswp-height="2500" target="_blank"> <img src="https://cdn.photoswipe.com/photoswipe-demo-images/photos/2/img-200.jpg" alt=""/> </a> <a href="https://cdn.photoswipe.com/photoswipe-demo-images/photos/7/img-2500.jpg" data-pswp-width="1875" data-pswp-height="2500" data-cropped="true" target="_blank"> <img src="https://cdn.photoswipe.com/photoswipe-demo-images/photos/7/img-200.jpg" alt=""/> </a> <a href="https://unsplash.com" data-pswp-src="https://cdn.photoswipe.com/photoswipe-demo-images/photos/3/img-2500.jpg" data-pswp-width="2500" data-pswp-height="1666" target="_blank"> <img src="https://cdn.photoswipe.com/photoswipe-demo-images/photos/3/img-200.jpg" alt=""/> </a> <div> <a href="https://cdn.photoswipe.com/photoswipe-demo-images/photos/6/img-2500.jpg" data-pswp-width="2500" data-pswp-height="1667" target="_blank"> <img src="https://cdn.photoswipe.com/photoswipe-demo-images/photos/6/img-200.jpg" alt=""/> </a> </div> </div> <hr/> <h2 id="spotlight-js"><a href="https://nextapps-de.github.io/spotlight/">Spotlight JS</a></h2> <div class="spotlight-group"> <a class="spotlight" href="https://cdn.photoswipe.com/photoswipe-demo-images/photos/1/img-2500.jpg"> <img src="https://cdn.photoswipe.com/photoswipe-demo-images/photos/1/img-200.jpg"/> </a> <a class="spotlight" href="https://cdn.photoswipe.com/photoswipe-demo-images/photos/2/img-2500.jpg"> <img src="https://cdn.photoswipe.com/photoswipe-demo-images/photos/2/img-200.jpg"/> </a> <a class="spotlight" href="https://cdn.photoswipe.com/photoswipe-demo-images/photos/3/img-2500.jpg"> <img src="https://cdn.photoswipe.com/photoswipe-demo-images/photos/3/img-200.jpg"/> </a> </div> <div class="spotlight-group"> <a class="spotlight" href="https://cdn.photoswipe.com/photoswipe-demo-images/photos/4/img-2500.jpg"> <img src="https://cdn.photoswipe.com/photoswipe-demo-images/photos/4/img-200.jpg"/> </a> <a class="spotlight" href="https://cdn.photoswipe.com/photoswipe-demo-images/photos/5/img-2500.jpg"> <img src="https://cdn.photoswipe.com/photoswipe-demo-images/photos/5/img-200.jpg"/> </a> <a class="spotlight" href="https://cdn.photoswipe.com/photoswipe-demo-images/photos/6/img-2500.jpg"> <img src="https://cdn.photoswipe.com/photoswipe-demo-images/photos/6/img-200.jpg"/> </a> </div> <hr/> <h2 id="venobox"><a href="https://veno.es/venobox/">Venobox</a></h2> <p><a class="venobox" data-gall="myGallery" href="https://cdn.photoswipe.com/photoswipe-demo-images/photos/1/img-2500.jpg"><img src="https://cdn.photoswipe.com/photoswipe-demo-images/photos/1/img-200.jpg"/></a> <a class="venobox" data-gall="myGallery" href="https://cdn.photoswipe.com/photoswipe-demo-images/photos/2/img-2500.jpg"><img src="https://cdn.photoswipe.com/photoswipe-demo-images/photos/2/img-200.jpg"/></a> <a class="venobox" data-gall="myGallery" href="https://cdn.photoswipe.com/photoswipe-demo-images/photos/3/img-2500.jpg"><img src="https://cdn.photoswipe.com/photoswipe-demo-images/photos/3/img-200.jpg"/></a></p>]]></content><author><name></name></author><category term="sample-posts"/><category term="formatting"/><category term="images"/><summary type="html"><![CDATA[this is what included image galleries could look like]]></summary></entry><entry><title type="html">a post with tabs</title><link href="https://cheems908.github.io/blog/2024/tabs/" rel="alternate" type="text/html" title="a post with tabs"/><published>2024-05-01T00:32:13+00:00</published><updated>2024-05-01T00:32:13+00:00</updated><id>https://cheems908.github.io/blog/2024/tabs</id><content type="html" xml:base="https://cheems908.github.io/blog/2024/tabs/"><![CDATA[<p>This is how a post with <a href="https://github.com/Ovski4/jekyll-tabs">tabs</a> looks like. Note that the tabs could be used for different purposes, not only for code.</p> <h2 id="first-tabs">First tabs</h2> <p>To add tabs, use the following syntax:</p> <div class="language-liquid highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">{%</span><span class="w"> </span><span class="nt">tabs</span><span class="w"> </span><span class="nv">group-name</span><span class="w"> </span><span class="cp">%}</span>

<span class="cp">{%</span><span class="w"> </span><span class="nt">tab</span><span class="w"> </span><span class="nv">group-name</span><span class="w"> </span><span class="nv">tab-name-1</span><span class="w"> </span><span class="cp">%}</span>

Content 1

<span class="cp">{%</span><span class="w"> </span><span class="nt">endtab</span><span class="w"> </span><span class="cp">%}</span>

<span class="cp">{%</span><span class="w"> </span><span class="nt">tab</span><span class="w"> </span><span class="nv">group-name</span><span class="w"> </span><span class="nv">tab-name-2</span><span class="w"> </span><span class="cp">%}</span>

Content 2

<span class="cp">{%</span><span class="w"> </span><span class="nt">endtab</span><span class="w"> </span><span class="cp">%}</span>

<span class="cp">{%</span><span class="w"> </span><span class="nt">endtabs</span><span class="w"> </span><span class="cp">%}</span>
</code></pre></div></div> <p>With this you can generate visualizations like:</p> <ul id="log" class="tab" data-tab="8ae0a2aa-2b29-4b45-902b-a6c92035002f" data-name="log"> <li class="active" id="log-php"> <a href="#">php </a> </li> <li id="log-js"> <a href="#">js </a> </li> <li id="log-ruby"> <a href="#">ruby </a> </li> </ul> <ul class="tab-content" id="8ae0a2aa-2b29-4b45-902b-a6c92035002f" data-name="log"> <li class="active"> <div class="language-php highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">var_dump</span><span class="p">(</span><span class="s1">'hello'</span><span class="p">);</span>
</code></pre></div></div> </li> <li> <div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">console</span><span class="p">.</span><span class="nf">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">hello</span><span class="dl">"</span><span class="p">);</span>
</code></pre></div></div> </li> <li> <div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">pputs</span> <span class="dl">'</span><span class="s1">hello</span><span class="dl">'</span>
</code></pre></div></div> </li> </ul> <h2 id="another-example">Another example</h2> <ul id="data-struct" class="tab" data-tab="cc143ad2-42de-40be-98e6-3d8f36fe34a6" data-name="data-struct"> <li class="active" id="data-struct-yaml"> <a href="#">yaml </a> </li> <li id="data-struct-json"> <a href="#">json </a> </li> </ul> <ul class="tab-content" id="cc143ad2-42de-40be-98e6-3d8f36fe34a6" data-name="data-struct"> <li class="active"> <div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">hello</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="s2">"</span><span class="s">whatsup"</span>
  <span class="pi">-</span> <span class="s2">"</span><span class="s">hi"</span>
</code></pre></div></div> </li> <li> <div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"hello"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"whatsup"</span><span class="p">,</span><span class="w"> </span><span class="s2">"hi"</span><span class="p">]</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div> </li> </ul> <h2 id="tabs-for-something-else">Tabs for something else</h2> <ul id="something-else" class="tab" data-tab="2717b9bc-7478-4aca-9195-669d62a52a20" data-name="something-else"> <li class="active" id="something-else-text"> <a href="#">text </a> </li> <li id="something-else-quote"> <a href="#">quote </a> </li> <li id="something-else-list"> <a href="#">list </a> </li> </ul> <ul class="tab-content" id="2717b9bc-7478-4aca-9195-669d62a52a20" data-name="something-else"> <li class="active"> <p>Regular text</p> </li> <li> <blockquote> <p>A quote</p> </blockquote> </li> <li> <p>Hipster list</p> <ul> <li>brunch</li> <li>fixie</li> <li>raybans</li> <li>messenger bag</li> </ul> </li> </ul>]]></content><author><name></name></author><category term="sample-posts"/><category term="formatting"/><category term="code"/><summary type="html"><![CDATA[this is what included tabs in a post could look like]]></summary></entry><entry><title type="html">a post with typograms</title><link href="https://cheems908.github.io/blog/2024/typograms/" rel="alternate" type="text/html" title="a post with typograms"/><published>2024-04-29T23:36:10+00:00</published><updated>2024-04-29T23:36:10+00:00</updated><id>https://cheems908.github.io/blog/2024/typograms</id><content type="html" xml:base="https://cheems908.github.io/blog/2024/typograms/"><![CDATA[<p>This is an example post with some <a href="https://github.com/google/typograms/">typograms</a> code.</p> <div class="language-markdown highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">```</span><span class="nl">typograms
</span><span class="sb">+----+
|    |---&gt; My first diagram!
+----+</span>
<span class="p">```</span>
</code></pre></div></div> <p>Which generates:</p> <pre><code class="language-typograms">+----+
|    |---&gt; My first diagram!
+----+
</code></pre> <p>Another example:</p> <div class="language-markdown highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">```</span><span class="nl">typograms
</span><span class="sb">.------------------------.
|.----------------------.|
||"https://example.com" ||
|'----------------------'|
| ______________________ |
||                      ||
||   Welcome!           ||
||                      ||
||                      ||
||  .----------------.  ||
||  | username       |  ||
||  '----------------'  ||
||  .----------------.  ||
||  |"*******"       |  ||
||  '----------------'  ||
||                      ||
||  .----------------.  ||
||  |   "Sign-up"    |  ||
||  '----------------'  ||
||                      ||
|+----------------------+|
.------------------------.</span>
<span class="p">```</span>
</code></pre></div></div> <p>which generates:</p> <pre><code class="language-typograms">.------------------------.
|.----------------------.|
||"https://example.com" ||
|'----------------------'|
| ______________________ |
||                      ||
||   Welcome!           ||
||                      ||
||                      ||
||  .----------------.  ||
||  | username       |  ||
||  '----------------'  ||
||  .----------------.  ||
||  |"*******"       |  ||
||  '----------------'  ||
||                      ||
||  .----------------.  ||
||  |   "Sign-up"    |  ||
||  '----------------'  ||
||                      ||
|+----------------------+|
.------------------------.
</code></pre> <p>For more examples, check out the <a href="https://google.github.io/typograms/#examples">typograms documentation</a>.</p>]]></content><author><name></name></author><category term="sample-posts"/><category term="formatting"/><category term="diagrams"/><summary type="html"><![CDATA[this is what included typograms code could look like]]></summary></entry><entry><title type="html">a post that can be cited</title><link href="https://cheems908.github.io/blog/2024/post-citation/" rel="alternate" type="text/html" title="a post that can be cited"/><published>2024-04-28T15:06:00+00:00</published><updated>2024-04-28T15:06:00+00:00</updated><id>https://cheems908.github.io/blog/2024/post-citation</id><content type="html" xml:base="https://cheems908.github.io/blog/2024/post-citation/"><![CDATA[<p>This is an example post that can be cited. The content of the post ends here, while the citation information is automatically provided below. The only thing needed is for you to set the <code class="language-plaintext highlighter-rouge">citation</code> key in the front matter to <code class="language-plaintext highlighter-rouge">true</code>.</p>]]></content><author><name></name></author><category term="sample-posts"/><category term="formatting"/><category term="citation"/><summary type="html"><![CDATA[this is what a post that can be cited looks like]]></summary></entry><entry><title type="html">a post with pseudo code</title><link href="https://cheems908.github.io/blog/2024/pseudocode/" rel="alternate" type="text/html" title="a post with pseudo code"/><published>2024-04-15T00:01:00+00:00</published><updated>2024-04-15T00:01:00+00:00</updated><id>https://cheems908.github.io/blog/2024/pseudocode</id><content type="html" xml:base="https://cheems908.github.io/blog/2024/pseudocode/"><![CDATA[<p>This is an example post with some pseudo code rendered by <a href="https://github.com/SaswatPadhi/pseudocode.js">pseudocode</a>. The example presented here is the same as the one in the <a href="https://saswat.padhi.me/pseudocode.js/">pseudocode.js</a> documentation, with only one simple but important change: everytime you would use <code class="language-plaintext highlighter-rouge">$</code>, you should use <code class="language-plaintext highlighter-rouge">$$</code> instead. Also, note that the <code class="language-plaintext highlighter-rouge">pseudocode</code> key in the front matter is set to <code class="language-plaintext highlighter-rouge">true</code> to enable the rendering of pseudo code. As an example, using this code:</p> <div class="language-markdown highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">```</span><span class="nl">pseudocode
</span><span class="sb">% This quicksort algorithm is extracted from Chapter 7, Introduction to Algorithms (3rd edition)
\begin{algorithm}
\caption{Quicksort}
\begin{algorithmic}
\PROCEDURE{Quicksort}{$$A, p, r$$}
    \IF{$$p &lt; r$$}
        \STATE $$q = $$ \CALL{Partition}{$$A, p, r$$}
        \STATE \CALL{Quicksort}{$$A, p, q - 1$$}
        \STATE \CALL{Quicksort}{$$A, q + 1, r$$}
    \ENDIF
\ENDPROCEDURE
\PROCEDURE{Partition}{$$A, p, r$$}
    \STATE $$x = A[r]$$
    \STATE $$i = p - 1$$
    \FOR{$$j = p$$ \TO $$r - 1$$}
        \IF{$$A[j] &lt; x$$}
            \STATE $$i = i + 1$$
            \STATE exchange
            $$A[i]$$ with $$A[j]$$
        \ENDIF
        \STATE exchange $$A[i]$$ with $$A[r]$$
    \ENDFOR
\ENDPROCEDURE
\end{algorithmic}
\end{algorithm}</span>
<span class="p">```</span>
</code></pre></div></div> <p>Generates:</p> <pre><code class="language-pseudocode">% This quicksort algorithm is extracted from Chapter 7, Introduction to Algorithms (3rd edition)
\begin{algorithm}
\caption{Quicksort}
\begin{algorithmic}
\PROCEDURE{Quicksort}{$$A, p, r$$}
    \IF{$$p &lt; r$$}
        \STATE $$q = $$ \CALL{Partition}{$$A, p, r$$}
        \STATE \CALL{Quicksort}{$$A, p, q - 1$$}
        \STATE \CALL{Quicksort}{$$A, q + 1, r$$}
    \ENDIF
\ENDPROCEDURE
\PROCEDURE{Partition}{$$A, p, r$$}
    \STATE $$x = A[r]$$
    \STATE $$i = p - 1$$
    \FOR{$$j = p$$ \TO $$r - 1$$}
        \IF{$$A[j] &lt; x$$}
            \STATE $$i = i + 1$$
            \STATE exchange
            $$A[i]$$ with $$A[j]$$
        \ENDIF
        \STATE exchange $$A[i]$$ with $$A[r]$$
    \ENDFOR
\ENDPROCEDURE
\end{algorithmic}
\end{algorithm}
</code></pre>]]></content><author><name></name></author><category term="sample-posts"/><category term="formatting"/><category term="code"/><summary type="html"><![CDATA[this is what included pseudo code could look like]]></summary></entry><entry><title type="html">a post with code diff</title><link href="https://cheems908.github.io/blog/2024/code-diff/" rel="alternate" type="text/html" title="a post with code diff"/><published>2024-01-27T19:22:00+00:00</published><updated>2024-01-27T19:22:00+00:00</updated><id>https://cheems908.github.io/blog/2024/code-diff</id><content type="html" xml:base="https://cheems908.github.io/blog/2024/code-diff/"><![CDATA[<p>You can display diff code by using the regular markdown syntax:</p> <div class="language-markdown highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">```</span><span class="nl">diff
</span><span class="gh">diff --git a/sample.js b/sample.js
index 0000001..0ddf2ba
</span><span class="gd">--- a/sample.js
</span><span class="gi">+++ b/sample.js
</span><span class="p">@@ -1 +1 @@</span>
<span class="gd">-console.log("Hello World!")
</span><span class="gi">+console.log("Hello from Diff2Html!")</span>
<span class="p">```</span>
</code></pre></div></div> <p>Which generates:</p> <div class="language-diff highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gh">diff --git a/sample.js b/sample.js
index 0000001..0ddf2ba
</span><span class="gd">--- a/sample.js
</span><span class="gi">+++ b/sample.js
</span><span class="p">@@ -1 +1 @@</span>
<span class="gd">-console.log("Hello World!")
</span><span class="gi">+console.log("Hello from Diff2Html!")
</span></code></pre></div></div> <p>But this is difficult to read, specially if you have a large diff. You can use <a href="https://diff2html.xyz/">diff2html</a> to display a more readable version of the diff. For this, just use <code class="language-plaintext highlighter-rouge">diff2html</code> instead of <code class="language-plaintext highlighter-rouge">diff</code> for the code block language:</p> <div class="language-markdown highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">```</span><span class="nl">diff2html
</span><span class="sb">diff --git a/sample.js b/sample.js
index 0000001..0ddf2ba
--- a/sample.js
+++ b/sample.js
@@ -1 +1 @@
-console.log("Hello World!")
+console.log("Hello from Diff2Html!")</span>
<span class="p">```</span>
</code></pre></div></div> <p>If we use a longer example, for example <a href="https://github.com/rtfpessoa/diff2html/commit/c2c253d3e3f8b8b267f551e659f72b44ca2ac927">this commit from diff2html</a>, it will generate the following output:</p> <pre><code class="language-diff2html">From 2aaae31cc2a37bfff83430c2c914b140bee59b6a Mon Sep 17 00:00:00 2001
From: Rodrigo Fernandes &lt;rtfrodrigo@gmail.com&gt;
Date: Sun, 9 Oct 2016 16:41:54 +0100
Subject: [PATCH 1/2] Initial template override support

---
 scripts/hulk.js                    |  4 ++--
 src/diff2html.js                   |  3 +--
 src/file-list-printer.js           | 11 ++++++++---
 src/hoganjs-utils.js               | 29 +++++++++++++++++------------
 src/html-printer.js                |  6 ++++++
 src/line-by-line-printer.js        |  6 +++++-
 src/side-by-side-printer.js        |  6 +++++-
 test/file-list-printer-tests.js    |  2 +-
 test/hogan-cache-tests.js          | 18 +++++++++++++++---
 test/line-by-line-tests.js         |  3 +--
 test/side-by-side-printer-tests.js |  3 +--
 11 files changed, 62 insertions(+), 29 deletions(-)

diff --git a/scripts/hulk.js b/scripts/hulk.js
index 5a793c18..a4b1a4d5 100755
--- a/scripts/hulk.js
+++ b/scripts/hulk.js
@@ -173,11 +173,11 @@ function namespace(name) {
 // write a template foreach file that matches template extension
 templates = extractFiles(options.argv.remain)
   .map(function(file) {
-    var openedFile = fs.readFileSync(file, 'utf-8');
+    var openedFile = fs.readFileSync(file, 'utf-8').trim();
     var name;
     if (!openedFile) return;
     name = namespace(path.basename(file).replace(/\..*$/, ''));
-    openedFile = removeByteOrderMark(openedFile.trim());
+    openedFile = removeByteOrderMark(openedFile);
     openedFile = wrap(file, name, openedFile);
     if (!options.outputdir) return openedFile;
     fs.writeFileSync(path.join(options.outputdir, name + '.js')
diff --git a/src/diff2html.js b/src/diff2html.js
index 21b0119e..64e138f5 100644
--- a/src/diff2html.js
+++ b/src/diff2html.js
@@ -7,7 +7,6 @@

 (function() {
   var diffParser = require('./diff-parser.js').DiffParser;
-  var fileLister = require('./file-list-printer.js').FileListPrinter;
   var htmlPrinter = require('./html-printer.js').HtmlPrinter;

   function Diff2Html() {
@@ -43,7 +42,7 @@

     var fileList = '';
     if (configOrEmpty.showFiles === true) {
-      fileList = fileLister.generateFileList(diffJson, configOrEmpty);
+      fileList = htmlPrinter.generateFileListSummary(diffJson, configOrEmpty);
     }

     var diffOutput = '';
diff --git a/src/file-list-printer.js b/src/file-list-printer.js
index e408d9b2..1e0a2c61 100644
--- a/src/file-list-printer.js
+++ b/src/file-list-printer.js
@@ -8,11 +8,16 @@
 (function() {
   var printerUtils = require('./printer-utils.js').PrinterUtils;

-  var hoganUtils = require('./hoganjs-utils.js').HoganJsUtils;
+  var hoganUtils;
+
   var baseTemplatesPath = 'file-summary';
   var iconsBaseTemplatesPath = 'icon';

-  function FileListPrinter() {
+  function FileListPrinter(config) {
+    this.config = config;
+
+    var HoganJsUtils = require('./hoganjs-utils.js').HoganJsUtils;
+    hoganUtils = new HoganJsUtils(config);
   }

   FileListPrinter.prototype.generateFileList = function(diffFiles) {
@@ -38,5 +43,5 @@
     });
   };

-  module.exports.FileListPrinter = new FileListPrinter();
+  module.exports.FileListPrinter = FileListPrinter;
 })();
diff --git a/src/hoganjs-utils.js b/src/hoganjs-utils.js
index 9949e5fa..0dda08d7 100644
--- a/src/hoganjs-utils.js
+++ b/src/hoganjs-utils.js
@@ -8,18 +8,19 @@
 (function() {
   var fs = require('fs');
   var path = require('path');
-
   var hogan = require('hogan.js');

   var hoganTemplates = require('./templates/diff2html-templates.js');

-  var templatesPath = path.resolve(__dirname, 'templates');
+  var extraTemplates;

-  function HoganJsUtils() {
+  function HoganJsUtils(configuration) {
+    this.config = configuration || {};
+    extraTemplates = this.config.templates || {};
   }

-  HoganJsUtils.prototype.render = function(namespace, view, params, configuration) {
-    var template = this.template(namespace, view, configuration);
+  HoganJsUtils.prototype.render = function(namespace, view, params) {
+    var template = this.template(namespace, view);
     if (template) {
       return template.render(params);
     }
@@ -27,17 +28,16 @@
     return null;
   };

-  HoganJsUtils.prototype.template = function(namespace, view, configuration) {
-    var config = configuration || {};
+  HoganJsUtils.prototype.template = function(namespace, view) {
     var templateKey = this._templateKey(namespace, view);

-    return this._getTemplate(templateKey, config);
+    return this._getTemplate(templateKey);
   };

-  HoganJsUtils.prototype._getTemplate = function(templateKey, config) {
+  HoganJsUtils.prototype._getTemplate = function(templateKey) {
     var template;

-    if (!config.noCache) {
+    if (!this.config.noCache) {
       template = this._readFromCache(templateKey);
     }

@@ -53,6 +53,7 @@

     try {
       if (fs.readFileSync) {
+        var templatesPath = path.resolve(__dirname, 'templates');
         var templatePath = path.join(templatesPath, templateKey);
         var templateContent = fs.readFileSync(templatePath + '.mustache', 'utf8');
         template = hogan.compile(templateContent);
@@ -66,12 +67,16 @@
   };

   HoganJsUtils.prototype._readFromCache = function(templateKey) {
-    return hoganTemplates[templateKey];
+    return extraTemplates[templateKey] || hoganTemplates[templateKey];
   };

   HoganJsUtils.prototype._templateKey = function(namespace, view) {
     return namespace + '-' + view;
   };

-  module.exports.HoganJsUtils = new HoganJsUtils();
+  HoganJsUtils.prototype.compile = function(templateStr) {
+    return hogan.compile(templateStr);
+  };
+
+  module.exports.HoganJsUtils = HoganJsUtils;
 })();
diff --git a/src/html-printer.js b/src/html-printer.js
index 585d5b66..13f83047 100644
--- a/src/html-printer.js
+++ b/src/html-printer.js
@@ -8,6 +8,7 @@
 (function() {
   var LineByLinePrinter = require('./line-by-line-printer.js').LineByLinePrinter;
   var SideBySidePrinter = require('./side-by-side-printer.js').SideBySidePrinter;
+  var FileListPrinter = require('./file-list-printer.js').FileListPrinter;

   function HtmlPrinter() {
   }
@@ -22,5 +23,10 @@
     return sideBySidePrinter.generateSideBySideJsonHtml(diffFiles);
   };

+  HtmlPrinter.prototype.generateFileListSummary = function(diffJson, config) {
+    var fileListPrinter = new FileListPrinter(config);
+    return fileListPrinter.generateFileList(diffJson);
+  };
+
   module.exports.HtmlPrinter = new HtmlPrinter();
 })();
diff --git a/src/line-by-line-printer.js b/src/line-by-line-printer.js
index b07eb53c..d230bedd 100644
--- a/src/line-by-line-printer.js
+++ b/src/line-by-line-printer.js
@@ -11,7 +11,8 @@
   var utils = require('./utils.js').Utils;
   var Rematch = require('./rematch.js').Rematch;

-  var hoganUtils = require('./hoganjs-utils.js').HoganJsUtils;
+  var hoganUtils;
+
   var genericTemplatesPath = 'generic';
   var baseTemplatesPath = 'line-by-line';
   var iconsBaseTemplatesPath = 'icon';
@@ -19,6 +20,9 @@

   function LineByLinePrinter(config) {
     this.config = config;
+
+    var HoganJsUtils = require('./hoganjs-utils.js').HoganJsUtils;
+    hoganUtils = new HoganJsUtils(config);
   }

   LineByLinePrinter.prototype.makeFileDiffHtml = function(file, diffs) {
diff --git a/src/side-by-side-printer.js b/src/side-by-side-printer.js
index bbf1dc8d..5e3033b3 100644
--- a/src/side-by-side-printer.js
+++ b/src/side-by-side-printer.js
@@ -11,7 +11,8 @@
   var utils = require('./utils.js').Utils;
   var Rematch = require('./rematch.js').Rematch;

-  var hoganUtils = require('./hoganjs-utils.js').HoganJsUtils;
+  var hoganUtils;
+
   var genericTemplatesPath = 'generic';
   var baseTemplatesPath = 'side-by-side';
   var iconsBaseTemplatesPath = 'icon';
@@ -26,6 +27,9 @@

   function SideBySidePrinter(config) {
     this.config = config;
+
+    var HoganJsUtils = require('./hoganjs-utils.js').HoganJsUtils;
+    hoganUtils = new HoganJsUtils(config);
   }

   SideBySidePrinter.prototype.makeDiffHtml = function(file, diffs) {
diff --git a/test/file-list-printer-tests.js b/test/file-list-printer-tests.js
index a502a46f..60ea3208 100644
--- a/test/file-list-printer-tests.js
+++ b/test/file-list-printer-tests.js
@@ -1,6 +1,6 @@
 var assert = require('assert');

-var fileListPrinter = require('../src/file-list-printer.js').FileListPrinter;
+var fileListPrinter = new (require('../src/file-list-printer.js').FileListPrinter)();

 describe('FileListPrinter', function() {
   describe('generateFileList', function() {
diff --git a/test/hogan-cache-tests.js b/test/hogan-cache-tests.js
index 190bf6f8..3bb754ac 100644
--- a/test/hogan-cache-tests.js
+++ b/test/hogan-cache-tests.js
@@ -1,6 +1,6 @@
 var assert = require('assert');

-var HoganJsUtils = require('../src/hoganjs-utils.js').HoganJsUtils;
+var HoganJsUtils = new (require('../src/hoganjs-utils.js').HoganJsUtils)();
 var diffParser = require('../src/diff-parser.js').DiffParser;

 describe('HoganJsUtils', function() {
@@ -21,16 +21,28 @@ describe('HoganJsUtils', function() {
       });
       assert.equal(emptyDiffHtml, result);
     });
+
     it('should render view without cache', function() {
       var result = HoganJsUtils.render('generic', 'empty-diff', {
         contentClass: 'd2h-code-line',
         diffParser: diffParser
       }, {noCache: true});
-      assert.equal(emptyDiffHtml + '\n', result);
+      assert.equal(emptyDiffHtml, result);
     });
+
     it('should return null if template is missing', function() {
-      var result = HoganJsUtils.render('generic', 'missing-template', {}, {noCache: true});
+      var hoganUtils = new (require('../src/hoganjs-utils.js').HoganJsUtils)({noCache: true});
+      var result = hoganUtils.render('generic', 'missing-template', {});
       assert.equal(null, result);
     });
+
+    it('should allow templates to be overridden', function() {
+      var emptyDiffTemplate = HoganJsUtils.compile('&lt;p&gt;&lt;/p&gt;');
+
+      var config = {templates: {'generic-empty-diff': emptyDiffTemplate}};
+      var hoganUtils = new (require('../src/hoganjs-utils.js').HoganJsUtils)(config);
+      var result = hoganUtils.render('generic', 'empty-diff', {myName: 'Rodrigo Fernandes'});
+      assert.equal('&lt;p&gt;Rodrigo Fernandes&lt;/p&gt;', result);
+    });
   });
 });
diff --git a/test/line-by-line-tests.js b/test/line-by-line-tests.js
index 1cd92073..8869b3df 100644
--- a/test/line-by-line-tests.js
+++ b/test/line-by-line-tests.js
@@ -14,7 +14,7 @@ describe('LineByLinePrinter', function() {
         '            File without changes\n' +
         '        &lt;/div&gt;\n' +
         '    &lt;/td&gt;\n' +
-        '&lt;/tr&gt;\n';
+        '&lt;/tr&gt;';

       assert.equal(expected, fileHtml);
     });
@@ -422,7 +422,6 @@ describe('LineByLinePrinter', function() {
         '        &lt;/div&gt;\n' +
         '    &lt;/td&gt;\n' +
         '&lt;/tr&gt;\n' +
-        '\n' +
         '                &lt;/tbody&gt;\n' +
         '            &lt;/table&gt;\n' +
         '        &lt;/div&gt;\n' +
diff --git a/test/side-by-side-printer-tests.js b/test/side-by-side-printer-tests.js
index 76625f8e..771daaa5 100644
--- a/test/side-by-side-printer-tests.js
+++ b/test/side-by-side-printer-tests.js
@@ -14,7 +14,7 @@ describe('SideBySidePrinter', function() {
         '            File without changes\n' +
         '        &lt;/div&gt;\n' +
         '    &lt;/td&gt;\n' +
-        '&lt;/tr&gt;\n';
+        '&lt;/tr&gt;';

       assert.equal(expectedRight, fileHtml.right);
       assert.equal(expectedLeft, fileHtml.left);
@@ -324,7 +324,6 @@ describe('SideBySidePrinter', function() {
         '        &lt;/div&gt;\n' +
         '    &lt;/td&gt;\n' +
         '&lt;/tr&gt;\n' +
-        '\n' +
         '                    &lt;/tbody&gt;\n' +
         '                &lt;/table&gt;\n' +
         '            &lt;/div&gt;\n' +

From f3cadb96677d0eb82fc2752dc3ffbf35ca9b5bdb Mon Sep 17 00:00:00 2001
From: Rodrigo Fernandes &lt;rtfrodrigo@gmail.com&gt;
Date: Sat, 15 Oct 2016 13:21:22 +0100
Subject: [PATCH 2/2] Allow uncompiled templates

---
 README.md                 |  3 +++
 src/hoganjs-utils.js      |  7 +++++++
 test/hogan-cache-tests.js | 24 +++++++++++++++++++++++-
 3 files changed, 33 insertions(+), 1 deletion(-)

diff --git a/README.md b/README.md
index 132c8a28..46909f25 100644
--- a/README.md
+++ b/README.md
@@ -98,6 +98,9 @@ The HTML output accepts a Javascript object with configuration. Possible options
   - `synchronisedScroll`: scroll both panes in side-by-side mode: `true` or `false`, default is `false`
   - `matchWordsThreshold`: similarity threshold for word matching, default is 0.25
   - `matchingMaxComparisons`: perform at most this much comparisons for line matching a block of changes, default is `2500`
+  - `templates`: object with previously compiled templates to replace parts of the html
+  - `rawTemplates`: object with raw not compiled templates to replace parts of the html
+  &gt; For more information regarding the possible templates look into [src/templates](https://github.com/rtfpessoa/diff2html/tree/master/src/templates)

 ## Diff2HtmlUI Helper

diff --git a/src/hoganjs-utils.js b/src/hoganjs-utils.js
index 0dda08d7..b2e9c275 100644
--- a/src/hoganjs-utils.js
+++ b/src/hoganjs-utils.js
@@ -17,6 +17,13 @@
   function HoganJsUtils(configuration) {
     this.config = configuration || {};
     extraTemplates = this.config.templates || {};
+
+    var rawTemplates = this.config.rawTemplates || {};
+    for (var templateName in rawTemplates) {
+      if (rawTemplates.hasOwnProperty(templateName)) {
+        if (!extraTemplates[templateName]) extraTemplates[templateName] = this.compile(rawTemplates[templateName]);
+      }
+    }
   }

   HoganJsUtils.prototype.render = function(namespace, view, params) {
diff --git a/test/hogan-cache-tests.js b/test/hogan-cache-tests.js
index 3bb754ac..a34839c0 100644
--- a/test/hogan-cache-tests.js
+++ b/test/hogan-cache-tests.js
@@ -36,7 +36,7 @@ describe('HoganJsUtils', function() {
       assert.equal(null, result);
     });

-    it('should allow templates to be overridden', function() {
+    it('should allow templates to be overridden with compiled templates', function() {
       var emptyDiffTemplate = HoganJsUtils.compile('&lt;p&gt;&lt;/p&gt;');

       var config = {templates: {'generic-empty-diff': emptyDiffTemplate}};
@@ -44,5 +44,27 @@ describe('HoganJsUtils', function() {
       var result = hoganUtils.render('generic', 'empty-diff', {myName: 'Rodrigo Fernandes'});
       assert.equal('&lt;p&gt;Rodrigo Fernandes&lt;/p&gt;', result);
     });
+
+    it('should allow templates to be overridden with uncompiled templates', function() {
+      var emptyDiffTemplate = '&lt;p&gt;&lt;/p&gt;';
+
+      var config = {rawTemplates: {'generic-empty-diff': emptyDiffTemplate}};
+      var hoganUtils = new (require('../src/hoganjs-utils.js').HoganJsUtils)(config);
+      var result = hoganUtils.render('generic', 'empty-diff', {myName: 'Rodrigo Fernandes'});
+      assert.equal('&lt;p&gt;Rodrigo Fernandes&lt;/p&gt;', result);
+    });
+
+    it('should allow templates to be overridden giving priority to compiled templates', function() {
+      var emptyDiffTemplate = HoganJsUtils.compile('&lt;p&gt;&lt;/p&gt;');
+      var emptyDiffTemplateUncompiled = '&lt;p&gt;Not used!&lt;/p&gt;';
+
+      var config = {
+        templates: {'generic-empty-diff': emptyDiffTemplate},
+        rawTemplates: {'generic-empty-diff': emptyDiffTemplateUncompiled}
+      };
+      var hoganUtils = new (require('../src/hoganjs-utils.js').HoganJsUtils)(config);
+      var result = hoganUtils.render('generic', 'empty-diff', {myName: 'Rodrigo Fernandes'});
+      assert.equal('&lt;p&gt;Rodrigo Fernandes&lt;/p&gt;', result);
+    });
   });
 });
</code></pre>]]></content><author><name></name></author><category term="sample-posts"/><category term="formatting"/><category term="code"/><summary type="html"><![CDATA[this is how you can display code diffs]]></summary></entry><entry><title type="html">a post with advanced image components</title><link href="https://cheems908.github.io/blog/2024/advanced-images/" rel="alternate" type="text/html" title="a post with advanced image components"/><published>2024-01-27T11:46:00+00:00</published><updated>2024-01-27T11:46:00+00:00</updated><id>https://cheems908.github.io/blog/2024/advanced-images</id><content type="html" xml:base="https://cheems908.github.io/blog/2024/advanced-images/"><![CDATA[<p>This is an example post with advanced image components.</p> <h2 id="image-slider">Image Slider</h2> <p>This is a simple image slider. It uses the <a href="https://swiperjs.com/">Swiper</a> library. Check the <a href="https://swiperjs.com/demos">examples page</a> for more information of what you can achieve with it.</p> <swiper-container keyboard="true" navigation="true" pagination="true" pagination-clickable="true" pagination-dynamic-bullets="true" rewind="true"> <swiper-slide> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/9-480.webp 480w,/assets/img/9-800.webp 800w,/assets/img/9-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/9.jpg" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </swiper-slide> <swiper-slide> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/7-480.webp 480w,/assets/img/7-800.webp 800w,/assets/img/7-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/7.jpg" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </swiper-slide> <swiper-slide> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/8-480.webp 480w,/assets/img/8-800.webp 800w,/assets/img/8-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/8.jpg" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </swiper-slide> <swiper-slide> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/10-480.webp 480w,/assets/img/10-800.webp 800w,/assets/img/10-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/10.jpg" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </swiper-slide> <swiper-slide> <figure> <picture> <source class="responsive-img-srcset" srcset="/assets/img/12-480.webp 480w,/assets/img/12-800.webp 800w,/assets/img/12-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/12.jpg" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="eager" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </swiper-slide> </swiper-container> <h2 id="image-comparison-slider">Image Comparison Slider</h2> <p>This is a simple image comparison slider. It uses the <a href="https://img-comparison-slider.sneas.io/">img-comparison-slider</a> library. Check the <a href="https://img-comparison-slider.sneas.io/examples.html">examples page</a> for more information of what you can achieve with it.</p> <img-comparison-slider> <figure slot="first"> <picture> <source class="responsive-img-srcset" srcset="/assets/img/prof_pic-480.webp 480w,/assets/img/prof_pic-800.webp 800w,/assets/img/prof_pic-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/prof_pic.jpg" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="lazy" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> <figure slot="second"> <picture> <source class="responsive-img-srcset" srcset="/assets/img/prof_pic_color-480.webp 480w,/assets/img/prof_pic_color-800.webp 800w,/assets/img/prof_pic_color-1400.webp 1400w," type="image/webp" sizes="95vw"/> <img src="/assets/img/prof_pic_color.png" class="img-fluid rounded z-depth-1" width="100%" height="auto" loading="lazy" onerror="this.onerror=null; $('.responsive-img-srcset').remove();"/> </picture> </figure> </img-comparison-slider>]]></content><author><name></name></author><category term="sample-posts"/><category term="formatting"/><category term="images"/><summary type="html"><![CDATA[this is what advanced image components could look like]]></summary></entry><entry><title type="html">a post with vega lite</title><link href="https://cheems908.github.io/blog/2024/vega-lite/" rel="alternate" type="text/html" title="a post with vega lite"/><published>2024-01-27T00:20:00+00:00</published><updated>2024-04-14T04:30:00+00:00</updated><id>https://cheems908.github.io/blog/2024/vega-lite</id><content type="html" xml:base="https://cheems908.github.io/blog/2024/vega-lite/"><![CDATA[<p>This is an example post with some <a href="https://vega.github.io/vega-lite/">vega lite</a> code.</p> <div class="language-markdown highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">```</span><span class="nl">vega_lite
</span><span class="sb">{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "description": "A dot plot showing each movie in the database, and the difference from the average movie rating. The display is sorted by year to visualize everything in sequential order. The graph is for all Movies before 2019.",
  "data": {
    "url": "https://raw.githubusercontent.com/vega/vega/main/docs/data/movies.json"
  },
  "transform": [
    {"filter": "datum['IMDB Rating'] != null"},
    {"filter": {"timeUnit": "year", "field": "Release Date", "range": [null, 2019]}},
    {
      "joinaggregate": [{
        "op": "mean",
        "field": "IMDB Rating",
        "as": "AverageRating"
      }]
    },
    {
      "calculate": "datum['IMDB Rating'] - datum.AverageRating",
      "as": "RatingDelta"
    }
  ],
  "mark": "point",
  "encoding": {
    "x": {
      "field": "Release Date",
      "type": "temporal"
    },
    "y": {
      "field": "RatingDelta",
      "type": "quantitative",
      "title": "Rating Delta"
    },
    "color": {
      "field": "RatingDelta",
      "type": "quantitative",
      "scale": {"domainMid": 0},
      "title": "Rating Delta"
    }
  }
}</span>
<span class="p">```</span>
</code></pre></div></div> <p>Which generates:</p> <pre><code class="language-vega_lite">{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "description": "A dot plot showing each movie in the database, and the difference from the average movie rating. The display is sorted by year to visualize everything in sequential order. The graph is for all Movies before 2019.",
  "data": {
    "url": "https://raw.githubusercontent.com/vega/vega/main/docs/data/movies.json"
  },
  "transform": [
    {"filter": "datum['IMDB Rating'] != null"},
    {"filter": {"timeUnit": "year", "field": "Release Date", "range": [null, 2019]}},
    {
      "joinaggregate": [{
        "op": "mean",
        "field": "IMDB Rating",
        "as": "AverageRating"
      }]
    },
    {
      "calculate": "datum['IMDB Rating'] - datum.AverageRating",
      "as": "RatingDelta"
    }
  ],
  "mark": "point",
  "encoding": {
    "x": {
      "field": "Release Date",
      "type": "temporal"
    },
    "y": {
      "field": "RatingDelta",
      "type": "quantitative",
      "title": "Rating Delta"
    },
    "color": {
      "field": "RatingDelta",
      "type": "quantitative",
      "scale": {"domainMid": 0},
      "title": "Rating Delta"
    }
  }
}
</code></pre> <p>This plot supports both light and dark themes.</p>]]></content><author><name></name></author><category term="sample-posts"/><category term="formatting"/><category term="charts"/><summary type="html"><![CDATA[this is what included vega lite code could look like]]></summary></entry></feed>