or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

base-classes.mdconfiguration.mddocument.mdfigures.mdindex.mdlayout.mdlists.mdmath.mdquantities.mdreferences.mdsectioning.mdtables.mdtext-formatting.mdtikz.mdutilities.md

math.mddocs/

0

# Mathematical Expressions

1

2

Mathematical typesetting with equations, matrices, aligned environments, and vector notation. PyLaTeX provides comprehensive support for LaTeX's mathematical capabilities, enabling the creation of complex equations, matrices, and mathematical symbols with proper formatting.

3

4

## Capabilities

5

6

### Math Environment

7

8

The Math class provides the foundation for mathematical expressions, supporting both inline and display math modes.

9

10

```python { .api }

11

class Math(Container):

12

def __init__(self, *, inline=False, data=None, escape=None):

13

"""

14

Create a math environment for equations.

15

16

Parameters:

17

- inline: bool, if True creates inline math ($...$), if False creates display math (\\[...\\])

18

- data: list or str, initial mathematical content

19

- escape: bool, whether to escape special characters (usually False for math)

20

21

Requires:

22

- amsmath package (automatically added)

23

"""

24

```

25

26

Usage example:

27

28

```python

29

from pylatex import Document, Section

30

from pylatex.math import Math

31

32

doc = Document()

33

34

with doc.create(Section('Mathematical Expressions')):

35

# Display math (block)

36

with doc.create(Math()) as math:

37

math.append(r'E = mc^2')

38

39

# Inline math

40

doc.append('The famous equation ')

41

doc.append(Math(data=r'E = mc^2', inline=True))

42

doc.append(' was derived by Einstein.')

43

44

# Complex expressions

45

with doc.create(Math()) as math:

46

math.append(r'\int_{-\infty}^{\infty} e^{-x^2} dx = \sqrt{\pi}')

47

```

48

49

### Aligned Equations

50

51

The Alignat environment creates aligned multi-line equations with proper spacing and alignment.

52

53

```python { .api }

54

class Alignat(Environment):

55

def __init__(self, aligns=2, numbering=True, escape=None):

56

"""

57

Create an aligned equation environment.

58

59

Parameters:

60

- aligns: int, number of alignment points (default 2)

61

- numbering: bool, whether to number equations

62

- escape: bool, whether to escape special characters

63

64

Requires:

65

- amsmath package (automatically added)

66

"""

67

```

68

69

Usage example:

70

71

```python

72

from pylatex import Document, Section, NoEscape

73

from pylatex.math import Alignat

74

75

doc = Document()

76

77

with doc.create(Section('System of Equations')):

78

# Basic aligned equations

79

with doc.create(Alignat(numbering=True)) as agn:

80

agn.append(r'2x + 3y &= 7 \\')

81

agn.append(r'x - y &= 1')

82

83

# Multiple alignment points

84

with doc.create(Alignat(aligns=3)) as agn:

85

agn.append(r'f(x) &= (x+a)(x+b) &= x^2 + (a+b)x + ab \\')

86

agn.append(r'g(x) &= (x-a)(x-b) &= x^2 - (a+b)x + ab')

87

88

# Unnumbered equations

89

with doc.create(Alignat(numbering=False)) as agn:

90

agn.append(r'\nabla \times \vec{E} &= -\frac{\partial \vec{B}}{\partial t} \\')

91

agn.append(r'\nabla \times \vec{B} &= \mu_0\vec{J} + \mu_0\epsilon_0\frac{\partial \vec{E}}{\partial t}')

92

```

93

94

### Matrix Environments

95

96

The Matrix class creates various types of mathematical matrices with automatic formatting.

97

98

```python { .api }

99

class Matrix(Environment):

100

def __init__(self, matrix, *, mtype="p", alignment=None):

101

"""

102

Create a matrix environment.

103

104

Parameters:

105

- matrix: numpy.ndarray, matrix data as numpy array

106

- mtype: str, matrix type:

107

- 'p': parentheses ()

108

- 'b': brackets []

109

- 'B': braces {}

110

- 'v': vertical bars ||

111

- 'V': double vertical bars ||||

112

- alignment: str, column alignment ('c', 'l', 'r')

113

114

Requires:

115

- amsmath package (automatically added)

116

"""

117

```

118

119

Usage example:

120

121

```python

122

import numpy as np

123

from pylatex import Document, Section, NoEscape

124

from pylatex.math import Matrix, Math

125

126

doc = Document()

127

128

with doc.create(Section('Matrices')):

129

# Basic matrix with parentheses (requires numpy)

130

matrix_data = np.array([[1, 2, 3],

131

[4, 5, 6],

132

[7, 8, 9]])

133

134

with doc.create(Math()) as math:

135

math.append('A = ')

136

math.append(Matrix(matrix_data, mtype='p'))

137

138

# Matrix with brackets

139

identity = [['1', '0', '0'],

140

['0', '1', '0'],

141

['0', '0', '1']]

142

143

with doc.create(Math()) as math:

144

math.append('I = ')

145

math.append(Matrix(identity, mtype='b'))

146

147

# Determinant with vertical bars

148

det_matrix = [['a', 'b'],

149

['c', 'd']]

150

151

with doc.create(Math()) as math:

152

math.append(r'\det(M) = ')

153

math.append(Matrix(det_matrix, mtype='v'))

154

math.append(' = ad - bc')

155

156

# Matrix with mathematical expressions

157

symbolic_matrix = [[NoEscape(r'\alpha'), NoEscape(r'\beta')],

158

[NoEscape(r'\gamma'), NoEscape(r'\delta')]]

159

160

with doc.create(Math()) as math:

161

math.append('Greek = ')

162

math.append(Matrix(symbolic_matrix, mtype='B'))

163

```

164

165

### Vector Notation

166

167

The VectorName class creates properly formatted vector names using LaTeX's mathbf command.

168

169

```python { .api }

170

class VectorName(Command):

171

def __init__(self, name):

172

"""

173

Create a bold vector name.

174

175

Parameters:

176

- name: str, vector name (will be rendered in bold math font)

177

"""

178

```

179

180

Usage example:

181

182

```python

183

from pylatex import Document, Section

184

from pylatex.math import Math, VectorName

185

186

doc = Document()

187

188

with doc.create(Section('Vector Operations')):

189

# Vector definitions

190

with doc.create(Math()) as math:

191

math.append(VectorName('v'))

192

math.append(' = ')

193

math.append(VectorName('a'))

194

math.append(' + ')

195

math.append(VectorName('b'))

196

197

# Vector components

198

with doc.create(Math()) as math:

199

math.append(VectorName('r'))

200

math.append(r' = \begin{pmatrix} x \\ y \\ z \end{pmatrix}')

201

202

# Cross product

203

with doc.create(Math()) as math:

204

math.append(VectorName('c'))

205

math.append(' = ')

206

math.append(VectorName('a'))

207

math.append(r' \times ')

208

math.append(VectorName('b'))

209

```

210

211

## Advanced Mathematical Constructs

212

213

### Complex Equations

214

215

```python

216

from pylatex import Document, Section, NoEscape

217

from pylatex.math import Math, Alignat

218

219

doc = Document()

220

221

with doc.create(Section('Advanced Mathematics')):

222

# Integral equations

223

with doc.create(Math()) as math:

224

math.append(NoEscape(r'''

225

\oint_{\partial S} \vec{F} \cdot d\vec{l} =

226

\iint_S (\nabla \times \vec{F}) \cdot \hat{n} \, dS

227

'''))

228

229

# Series expansions

230

with doc.create(Math()) as math:

231

math.append(NoEscape(r'''

232

e^x = \sum_{n=0}^{\infty} \frac{x^n}{n!} =

233

1 + x + \frac{x^2}{2!} + \frac{x^3}{3!} + \cdots

234

'''))

235

236

# Limit definitions

237

with doc.create(Math()) as math:

238

math.append(NoEscape(r'''

239

\lim_{h \to 0} \frac{f(x+h) - f(x)}{h} = f'(x)

240

'''))

241

```

242

243

### Matrix Operations

244

245

```python

246

import numpy as np

247

from pylatex import Document, Section, NoEscape

248

from pylatex.math import Math, Matrix

249

250

doc = Document()

251

252

with doc.create(Section('Matrix Operations')):

253

# Matrix multiplication (symbolic)

254

A = np.array([['a_{11}', 'a_{12}'],

255

['a_{21}', 'a_{22}']])

256

B = np.array([['b_{11}', 'b_{12}'],

257

['b_{21}', 'b_{22}']])

258

259

with doc.create(Math()) as math:

260

math.append('AB = ')

261

math.append(Matrix(A, mtype='b'))

262

math.append(Matrix(B, mtype='b'))

263

math.append(' = ')

264

result = [['a_{11}b_{11} + a_{12}b_{21}', 'a_{11}b_{12} + a_{12}b_{22}'],

265

['a_{21}b_{11} + a_{22}b_{21}', 'a_{21}b_{12} + a_{22}b_{22}']]

266

math.append(Matrix(result, mtype='b'))

267

268

# Eigenvalue equation

269

with doc.create(Math()) as math:

270

math.append('A')

271

math.append(VectorName('v'))

272

math.append(r' = \lambda ')

273

math.append(VectorName('v'))

274

```

275

276

### Systems of Equations

277

278

```python

279

from pylatex import Document, Section, NoEscape

280

from pylatex.math import Alignat

281

282

doc = Document()

283

284

with doc.create(Section('Linear Systems')):

285

# Augmented matrix representation

286

with doc.create(Alignat(aligns=4, numbering=False)) as agn:

287

agn.append(r'2x &+ 3y &- z &= 7 \\')

288

agn.append(r'x &- y &+ 2z &= 3 \\')

289

agn.append(r'3x &+ 2y &+ z &= 8')

290

291

# Solution steps

292

with doc.create(Alignat(numbering=False)) as agn:

293

agn.append(r'x &= \frac{D_x}{D} \\')

294

agn.append(r'y &= \frac{D_y}{D} \\')

295

agn.append(r'z &= \frac{D_z}{D}')

296

```

297

298

## Mathematical Symbols and Notation

299

300

### Common Mathematical Constructs

301

302

```python

303

from pylatex import Document, Section, NoEscape

304

from pylatex.math import Math

305

306

doc = Document()

307

308

# Greek letters and symbols

309

with doc.create(Math()) as math:

310

math.append(NoEscape(r'\alpha, \beta, \gamma, \delta, \epsilon'))

311

312

# Calculus notation

313

with doc.create(Math()) as math:

314

math.append(NoEscape(r'\frac{d}{dx}f(x), \frac{\partial}{\partial x}f(x,y)'))

315

316

# Set theory

317

with doc.create(Math()) as math:

318

math.append(NoEscape(r'A \cup B, A \cap B, A \subset B, x \in A'))

319

320

# Logic symbols

321

with doc.create(Math()) as math:

322

math.append(NoEscape(r'\forall x \in \mathbb{R}, \exists y \in \mathbb{N}'))

323

324

# Operators

325

with doc.create(Math()) as math:

326

math.append(NoEscape(r'\sum_{i=1}^{n} x_i, \prod_{i=1}^{n} x_i, \int_a^b f(x)dx'))

327

```

328

329

### Custom Mathematical Functions

330

331

```python

332

from pylatex import Document, Command, NoEscape

333

from pylatex.math import Math

334

335

doc = Document()

336

337

# Define custom operators

338

doc.preamble.append(Command('DeclareMathOperator', arguments=[NoEscape(r'\Tr'), 'Tr']))

339

doc.preamble.append(Command('DeclareMathOperator', arguments=[NoEscape(r'\rank'), 'rank']))

340

341

with doc.create(Math()) as math:

342

math.append(NoEscape(r'\Tr(A) = \sum_{i} A_{ii}'))

343

344

with doc.create(Math()) as math:

345

math.append(NoEscape(r'\rank(A) \leq \min(m, n)'))

346

```

347

348

## Equation Numbering and References

349

350

### Numbered Equations

351

352

```python

353

from pylatex import Document, Section, NoEscape

354

from pylatex.math import Alignat

355

from pylatex import Label, Ref

356

357

doc = Document()

358

359

with doc.create(Section('Referenced Equations')):

360

# Numbered alignat environment

361

with doc.create(Alignat()) as agn:

362

agn.append(NoEscape(r'E &= mc^2'))

363

agn.append(Label('einstein'))

364

agn.append(NoEscape(r'\\'))

365

agn.append(NoEscape(r'F &= ma'))

366

agn.append(Label('newton'))

367

368

doc.append(NoEscape('Einstein\'s equation '))

369

doc.append(Ref('einstein'))

370

doc.append(NoEscape(' and Newton\'s law '))

371

doc.append(Ref('newton'))

372

doc.append(NoEscape(' are fundamental to physics.'))

373

```

374

375

## Package Dependencies

376

377

Mathematical environments automatically include necessary packages:

378

379

- **Math, Alignat, Matrix**: `amsmath` package (automatically added)

380

- **Additional symbols**: May require `amssymb`, `amsfonts`

381

- **Bold math**: `bm` package for bold mathematical symbols

382

- **Custom operators**: Use `\DeclareMathOperator` in preamble

383

384

```python

385

from pylatex import Document, Package

386

387

doc = Document()

388

doc.packages.append(Package('amsmath'))

389

doc.packages.append(Package('amssymb'))

390

doc.packages.append(Package('amsfonts'))

391

doc.packages.append(Package('bm'))

392

```

393

394

## Mathematical Best Practices

395

396

### Equation Formatting

397

398

```python

399

from pylatex import Document, NoEscape

400

from pylatex.math import Math, Alignat

401

402

# Use proper spacing

403

with doc.create(Math()) as math:

404

math.append(NoEscape(r'a \cdot b \quad \text{not} \quad a.b'))

405

406

# Use text in equations

407

with doc.create(Math()) as math:

408

math.append(NoEscape(r'P(\text{event}) = \frac{\text{favorable outcomes}}{\text{total outcomes}}'))

409

410

# Break long equations

411

with doc.create(Alignat(numbering=False)) as agn:

412

agn.append(NoEscape(r'f(x) &= a_0 + a_1x + a_2x^2 + a_3x^3 \\'))

413

agn.append(NoEscape(r'&\quad + a_4x^4 + a_5x^5 + \cdots'))

414

```

415

416

Mathematical expressions in PyLaTeX maintain LaTeX's high-quality typesetting while providing programmatic control over equation generation and formatting.