or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-arithmetic.mdelementary-functions.mdelliptic-modular-functions.mdindex.mdlinear-algebra.mdmathematical-constants.mdnumerical-calculus.mdpattern-recognition.mdsignal-processing.mdspecial-functions.mdvisualization.md

core-arithmetic.mddocs/

0

# Core Arithmetic

1

2

Basic number types, arithmetic operations, precision control, and utility functions that form the foundation for all mathematical computations in mpmath.

3

4

## Capabilities

5

6

### Number Type Creation

7

8

Create multiprecision floating-point and complex numbers from various input types.

9

10

```python { .api }

11

class mpf:

12

"""

13

Multiprecision floating-point number.

14

15

Args:

16

x: Input value (int, float, str, mpf, or fraction)

17

"""

18

def __init__(self, x): ...

19

20

class mpc:

21

"""

22

Multiprecision complex number.

23

24

Args:

25

real: Real part (number or string)

26

imag: Imaginary part (number or string), default 0

27

"""

28

def __init__(self, real, imag=0): ...

29

30

def mpmathify(x):

31

"""

32

Convert input to appropriate mpmath number type.

33

34

Args:

35

x: Value to convert

36

37

Returns:

38

mpf, mpc, or original type as appropriate

39

"""

40

41

# Alias for mpmathify

42

convert = mpmathify

43

```

44

45

### Precision Control

46

47

Control precision settings globally or within specific contexts.

48

49

```python { .api }

50

def extraprec(n):

51

"""

52

Context manager to temporarily increase precision by n bits.

53

54

Args:

55

n (int): Additional precision in bits

56

"""

57

58

def extradps(n):

59

"""

60

Context manager to temporarily increase precision by n decimal places.

61

62

Args:

63

n (int): Additional precision in decimal places

64

"""

65

66

def workprec(n):

67

"""

68

Context manager to set working precision to n bits.

69

70

Args:

71

n (int): Precision in bits

72

"""

73

74

def workdps(n):

75

"""

76

Context manager to set working precision to n decimal places.

77

78

Args:

79

n (int): Precision in decimal places

80

"""

81

82

def autoprec(f):

83

"""

84

Decorator for automatic precision adjustment.

85

86

Args:

87

f: Function to decorate

88

"""

89

90

def maxcalls(n):

91

"""

92

Context manager to limit function evaluation calls.

93

94

Args:

95

n (int): Maximum number of calls

96

"""

97

98

def memoize(f):

99

"""

100

Decorator to add memoization to a function.

101

102

Args:

103

f: Function to memoize

104

"""

105

```

106

107

### Basic Arithmetic Operations

108

109

Low-level arithmetic operations for maximum control and efficiency.

110

111

```python { .api }

112

def fadd(x, y):

113

"""

114

Add two numbers.

115

116

Args:

117

x, y: Numbers to add

118

119

Returns:

120

Sum of x and y

121

"""

122

123

def fsub(x, y):

124

"""

125

Subtract y from x.

126

127

Args:

128

x, y: Numbers for subtraction

129

130

Returns:

131

Difference x - y

132

"""

133

134

def fmul(x, y):

135

"""

136

Multiply two numbers.

137

138

Args:

139

x, y: Numbers to multiply

140

141

Returns:

142

Product of x and y

143

"""

144

145

def fdiv(x, y):

146

"""

147

Divide x by y.

148

149

Args:

150

x, y: Numbers for division

151

152

Returns:

153

Quotient x / y

154

"""

155

156

def fneg(x):

157

"""

158

Negate a number.

159

160

Args:

161

x: Number to negate

162

163

Returns:

164

-x

165

"""

166

167

def fprod(sequence):

168

"""

169

Compute product of sequence of numbers.

170

171

Args:

172

sequence: Iterable of numbers

173

174

Returns:

175

Product of all numbers in sequence

176

"""

177

178

def fsum(sequence):

179

"""

180

Accurately sum a sequence of numbers.

181

182

Args:

183

sequence: Iterable of numbers

184

185

Returns:

186

Sum of all numbers in sequence

187

"""

188

189

def fdot(x, y):

190

"""

191

Compute dot product of two sequences.

192

193

Args:

194

x, y: Sequences of numbers

195

196

Returns:

197

Dot product sum(x[i] * y[i])

198

"""

199

```

200

201

### Number Properties and Testing

202

203

Functions to test properties of numbers and extract information.

204

205

```python { .api }

206

def isinf(x):

207

"""

208

Test if x is infinite.

209

210

Args:

211

x: Number to test

212

213

Returns:

214

bool: True if x is infinite

215

"""

216

217

def isnan(x):

218

"""

219

Test if x is NaN (not a number).

220

221

Args:

222

x: Number to test

223

224

Returns:

225

bool: True if x is NaN

226

"""

227

228

def isnormal(x):

229

"""

230

Test if x is a normal number.

231

232

Args:

233

x: Number to test

234

235

Returns:

236

bool: True if x is normal

237

"""

238

239

def isint(x):

240

"""

241

Test if x is an integer.

242

243

Args:

244

x: Number to test

245

246

Returns:

247

bool: True if x is an integer

248

"""

249

250

def isfinite(x):

251

"""

252

Test if x is finite.

253

254

Args:

255

x: Number to test

256

257

Returns:

258

bool: True if x is finite

259

"""

260

261

def almosteq(x, y, rel_eps=None, abs_eps=None):

262

"""

263

Test if two numbers are approximately equal.

264

265

Args:

266

x, y: Numbers to compare

267

rel_eps: Relative tolerance

268

abs_eps: Absolute tolerance

269

270

Returns:

271

bool: True if numbers are approximately equal

272

"""

273

274

def sign(x):

275

"""

276

Return the sign of x.

277

278

Args:

279

x: Number

280

281

Returns:

282

-1, 0, or 1 depending on sign of x

283

"""

284

285

def mag(x):

286

"""

287

Return the magnitude (order of magnitude) of x.

288

289

Args:

290

x: Number

291

292

Returns:

293

int: Magnitude of x

294

"""

295

```

296

297

### Complex Number Operations

298

299

Operations specific to complex numbers.

300

301

```python { .api }

302

def re(z):

303

"""

304

Return real part of complex number.

305

306

Args:

307

z: Complex number

308

309

Returns:

310

Real part of z

311

"""

312

313

def im(z):

314

"""

315

Return imaginary part of complex number.

316

317

Args:

318

z: Complex number

319

320

Returns:

321

Imaginary part of z

322

"""

323

324

def conj(z):

325

"""

326

Return complex conjugate.

327

328

Args:

329

z: Complex number

330

331

Returns:

332

Complex conjugate of z

333

"""

334

335

def arg(z):

336

"""

337

Return argument (phase) of complex number.

338

339

Args:

340

z: Complex number

341

342

Returns:

343

Argument of z in radians

344

"""

345

346

def phase(z):

347

"""

348

Return phase of complex number (alias for arg).

349

350

Args:

351

z: Complex number

352

353

Returns:

354

Phase of z in radians

355

"""

356

357

def polar(z):

358

"""

359

Convert complex number to polar form.

360

361

Args:

362

z: Complex number

363

364

Returns:

365

tuple: (magnitude, phase)

366

"""

367

368

def rect(r, phi):

369

"""

370

Convert from polar to rectangular form.

371

372

Args:

373

r: Magnitude

374

phi: Phase in radians

375

376

Returns:

377

Complex number in rectangular form

378

"""

379

```

380

381

### Display and Formatting

382

383

Functions for controlling number display and string conversion.

384

385

```python { .api }

386

def nstr(x, n=None, **kwargs):

387

"""

388

Convert number to string with specified precision.

389

390

Args:

391

x: Number to convert

392

n: Number of digits to display

393

**kwargs: Additional formatting options

394

395

Returns:

396

str: String representation of number

397

"""

398

399

def nprint(x, n=None, **kwargs):

400

"""

401

Print number with specified precision.

402

403

Args:

404

x: Number to print

405

n: Number of digits to display

406

**kwargs: Additional formatting options

407

"""

408

409

def chop(x, tol=None):

410

"""

411

Round small numbers to zero.

412

413

Args:

414

x: Number to chop

415

tol: Tolerance for chopping

416

417

Returns:

418

Number with small values rounded to zero

419

"""

420

```

421

422

### Utility Functions

423

424

Miscellaneous utility functions for working with numbers.

425

426

```python { .api }

427

def fraction(x, tol=None):

428

"""

429

Convert number to rational fraction representation.

430

431

Args:

432

x: Number to convert

433

tol: Tolerance for conversion

434

435

Returns:

436

Rational representation as (numerator, denominator)

437

"""

438

439

def rand():

440

"""

441

Generate random number between 0 and 1.

442

443

Returns:

444

Random mpf between 0 and 1

445

"""

446

447

def linspace(a, b, n):

448

"""

449

Generate linearly spaced array.

450

451

Args:

452

a: Start value

453

b: End value

454

n: Number of points

455

456

Returns:

457

list: Array of n evenly spaced values

458

"""

459

460

def arange(start, stop=None, step=1):

461

"""

462

Generate arithmetic progression.

463

464

Args:

465

start: Start value (or stop if stop is None)

466

stop: End value (optional)

467

step: Step size

468

469

Returns:

470

list: Arithmetic progression

471

"""

472

473

def absmin(*args):

474

"""

475

Return argument with minimum absolute value.

476

477

Args:

478

*args: Numbers to compare

479

480

Returns:

481

Number with minimum absolute value

482

"""

483

484

def absmax(*args):

485

"""

486

Return argument with maximum absolute value.

487

488

Args:

489

*args: Numbers to compare

490

491

Returns:

492

Number with maximum absolute value

493

"""

494

495

def nint_distance(x):

496

"""

497

Return distance to nearest integer.

498

499

Args:

500

x: Number

501

502

Returns:

503

Distance to nearest integer

504

"""

505

506

def make_mpf(s):

507

"""

508

Create mpf number from internal representation.

509

510

Args:

511

s: Internal representation

512

513

Returns:

514

mpf number

515

"""

516

517

def make_mpc(real, imag=None):

518

"""

519

Create mpc number from components.

520

521

Args:

522

real: Real part

523

imag: Imaginary part (optional)

524

525

Returns:

526

mpc number

527

"""

528

529

# Package version

530

__version__ # Version string of mpmath package

531

```

532

533

### Context Objects

534

535

Arithmetic contexts that control precision and behavior of mathematical operations.

536

537

```python { .api }

538

# Main contexts

539

mp # MPContext - multiprecision arithmetic (default)

540

fp # FPContext - fast double-precision arithmetic

541

iv # MPIntervalContext - interval arithmetic

542

543

class MPContext:

544

"""

545

Multiprecision arithmetic context with configurable precision.

546

547

Attributes:

548

dps: Decimal precision (number of decimal places)

549

prec: Binary precision (number of bits)

550

pretty: Pretty printing mode

551

"""

552

553

def workprec(self, n):

554

"""Context manager for temporary precision change."""

555

556

def workdps(self, n):

557

"""Context manager for temporary decimal precision change."""

558

559

def extraprec(self, n):

560

"""Context manager for additional precision."""

561

562

class FPContext:

563

"""

564

Fast double-precision floating-point context.

565

Uses hardware floating-point for maximum speed.

566

"""

567

568

class MPIntervalContext:

569

"""

570

Interval arithmetic context for rigorous computation.

571

All operations return intervals containing exact results.

572

"""

573

574

# Interval number type

575

class mpi:

576

"""

577

Multiprecision interval [a, b].

578

579

Args:

580

a: Lower bound

581

b: Upper bound (optional, defaults to a)

582

"""

583

def __init__(self, a, b=None): ...

584

```

585

586

### Special Constants

587

588

Basic mathematical constants and special values.

589

590

```python { .api }

591

# Special values

592

inf # Positive infinity

593

ninf # Negative infinity

594

nan # Not a number

595

j # Imaginary unit

596

eps # Machine epsilon

597

```

598

599

### Usage Examples

600

601

```python

602

import mpmath

603

from mpmath import mp, mpf, mpc

604

605

# Set precision

606

mp.dps = 30 # 30 decimal places

607

608

# Create high-precision numbers

609

x = mpf('1.23456789012345678901234567890')

610

y = mpf(2) # Can use regular numbers too

611

612

# Basic arithmetic

613

print(f"Sum: {x + y}")

614

print(f"Product: {x * y}")

615

616

# Complex numbers

617

z1 = mpc(1, 2) # 1 + 2j

618

z2 = mpc('3.14159', '2.71828')

619

print(f"Complex sum: {z1 + z2}")

620

621

# Precision control

622

with mp.workdps(50): # Temporarily use 50 decimal places

623

high_precision_result = mpf(1) / mpf(3)

624

print(f"1/3 with 50 digits: {high_precision_result}")

625

626

# Testing number properties

627

print(f"Is {x} finite? {mp.isfinite(x)}")

628

print(f"Is infinity finite? {mp.isfinite(mp.inf)}")

629

630

# Complex number operations

631

z = mpc(3, 4)

632

print(f"Magnitude: {abs(z)}")

633

print(f"Phase: {mp.arg(z)}")

634

print(f"Real part: {mp.re(z)}")

635

print(f"Imaginary part: {mp.im(z)}")

636

```