代码与公式展示

代码与公式展示

这是一个用于展示代码片段和数学公式的页面,使用安知鱼主题自带的代码高亮样式。

代码示例

Python - 快速排序

1
2
3
4
5
6
7
8
9
# Python 示例:快速排序算法
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)

C++ - 矩阵乘法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <vector>

using namespace std;

// 矩阵乘法
vector<vector<int>> matrixMultiply(
const vector<vector<int>>& A,
const vector<vector<int>>& B
) {
int n = A.size();
int m = B[0].size();
int k = B.size();
vector<vector<int>> C(n, vector<int>(m, 0));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
for (int p = 0; p < k; ++p) {
C[i][j] += A[i][p] * B[p][j];
}
}
}
return C;
}

Python - 机器学习

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 机器学习示例:线性回归
import numpy as np

class LinearRegression:
"""线性回归模型"""

def __init__(self, learning_rate=0.01, n_iterations=1000):
self.learning_rate = learning_rate
self.n_iterations = n_iterations
self.weights = None
self.bias = None

def fit(self, X, y):
"""训练模型"""
n_samples, n_features = X.shape
self.weights = np.zeros(n_features)
self.bias = 0

for _ in range(self.n_iterations):
y_pred = np.dot(X, self.weights) + self.bias
dw = (1 / n_samples) * np.dot(X.T, (y_pred - y))
db = (1 / n_samples) * np.sum(y_pred - y)
self.weights -= self.learning_rate * dw
self.bias -= self.learning_rate * db

def predict(self, X):
"""预测"""
return np.dot(X, self.weights) + self.bias

数学公式示例

行内公式

爱因斯坦的质能方程:$E = mc^2$,其中 $E$ 是能量,$m$ 是质量,$c$ 是光速。

高斯积分

$$ \int_{-\infty}^{\infty} e^{-x^2} dx = \sqrt{\pi} $$

矩阵表示

$$ \mathbf{A} = \begin{pmatrix} a_{11} & a_{12} & \cdots & a_{1n} \\ a_{21} & a_{22} & \cdots & a_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ a_{m1} & a_{m2} & \cdots & a_{mn} \end{pmatrix} $$

热传导方程

$$ \frac{\partial u}{\partial t} = \alpha \nabla^2 u $$

正态分布

$$ f(x) = \frac{1}{\sigma\sqrt{2\pi}} e^{-\frac{1}{2}\left(\frac{x-\mu}{\sigma}\right)^2} $$

线性回归损失函数

$$ J(\theta) = \frac{1}{2m} \sum_{i=1}^{m} (h_\theta(x^{(i)}) - y^{(i)})^2 $$

对应上面 Python 代码中的损失函数

使用说明

代码展示

页面使用安知鱼主题自带的代码高亮,支持:

  • 语法高亮 - 使用主题配置的 mac 风格
  • 多语言支持 - Python、C++、Java、JavaScript 等
  • 复制按钮 - 一键复制代码
  • 语言标识 - 显示代码语言
  • 代码折叠 - 可折叠代码块
  • 高度限制 - 超过限制自动折叠

公式导航

页面提供了公式导航目录,点击可以快速跳转到对应的公式位置。

添加代码块

使用 Markdown 标准语法:

1
2
3
4
5
```python
# Python 代码示例
def hello():
print("Hello World")
```

主题配置

在主题配置文件中修改代码块样式(themes/hexo-theme-anzhiyu-dev/_config.yml):

1
2
3
4
5
6
highlight_theme: mac # darker / pale night / light / ocean / mac / mac light / false
highlight_copy: true # 复制按钮
highlight_lang: true # 语言标识
highlight_shrink: false # 代码折叠
highlight_height_limit: 330 # 高度限制(px)
code_word_wrap: false # 自动换行