or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

arithmetic.mdbit-operations.mdcontext.mddata-types.mdindex.mdmath-functions.mdnumber-theory.mdrandom.mdutilities.md

data-types.mddocs/

0

# Multiple-Precision Data Types

1

2

gmpy2 provides five main data types for different kinds of multiple-precision arithmetic. Each type integrates seamlessly with Python's numeric protocols while providing access to high-performance arbitrary-precision operations.

3

4

## Capabilities

5

6

### mpz - Multiple-Precision Integer

7

8

Immutable arbitrary-precision integers based on the GMP library. Supports all standard integer operations with unlimited precision.

9

10

```python { .api }

11

class mpz:

12

def __init__(self, x=0, base=10):

13

"""

14

Create multiple-precision integer.

15

16

Args:

17

x: Initial value (int, str, bytes, or numeric type)

18

base: Base for string conversion (2-62)

19

"""

20

21

# Bit operations

22

def bit_clear(self, index: int) -> 'mpz':

23

"""Clear bit at specified index, return new mpz."""

24

25

def bit_count(self) -> int:

26

"""Count number of set bits (population count)."""

27

28

def bit_flip(self, index: int) -> 'mpz':

29

"""Flip bit at specified index, return new mpz."""

30

31

def bit_length(self) -> int:

32

"""Number of bits needed to represent the number."""

33

34

def bit_scan0(self, start: int = 0) -> int:

35

"""Find first clear bit starting from position."""

36

37

def bit_scan1(self, start: int = 0) -> int:

38

"""Find first set bit starting from position."""

39

40

def bit_set(self, index: int) -> 'mpz':

41

"""Set bit at specified index, return new mpz."""

42

43

def bit_test(self, index: int) -> bool:

44

"""Test if bit is set at specified index."""

45

46

# Number theory methods

47

def is_congruent(self, y, m) -> bool:

48

"""Test if self ≡ y (mod m)."""

49

50

def is_divisible(self, y) -> bool:

51

"""Test if self is divisible by y."""

52

53

def is_even(self) -> bool:

54

"""Test if number is even."""

55

56

def is_odd(self) -> bool:

57

"""Test if number is odd."""

58

59

def is_power(self) -> bool:

60

"""Test if number is a perfect power."""

61

62

def is_prime(self, n: int = 25) -> bool:

63

"""

64

Primality test using Miller-Rabin algorithm.

65

66

Args:

67

n: Number of test rounds (higher = more accurate)

68

69

Returns:

70

True if probably prime, False if composite

71

"""

72

73

def is_probab_prime(self, n: int = 25) -> int:

74

"""

75

Probabilistic primality test.

76

77

Returns:

78

0 if composite, 1 if probably prime, 2 if definitely prime

79

"""

80

81

def is_square(self) -> bool:

82

"""Test if number is a perfect square."""

83

84

# Conversion and representation

85

def digits(self, base: int = 10) -> str:

86

"""Return string representation in specified base."""

87

88

def num_digits(self, base: int = 10) -> int:

89

"""Count digits in specified base."""

90

91

def to_bytes(self, length: int = 1, byteorder: str = 'big', signed: bool = False) -> bytes:

92

"""Convert to bytes representation."""

93

94

@classmethod

95

def from_bytes(cls, bytes_data: bytes, byteorder: str = 'big', signed: bool = False) -> 'mpz':

96

"""Create mpz from bytes representation."""

97

98

# Rational interface compatibility

99

def as_integer_ratio(self) -> tuple:

100

"""Return (numerator, denominator) tuple - (self, 1)."""

101

102

@property

103

def numerator(self) -> 'mpz':

104

"""Numerator (returns self)."""

105

106

@property

107

def denominator(self) -> 'mpz':

108

"""Denominator (returns 1)."""

109

110

# Complex interface compatibility

111

@property

112

def real(self) -> 'mpz':

113

"""Real part (returns self)."""

114

115

@property

116

def imag(self) -> 'mpz':

117

"""Imaginary part (returns 0)."""

118

119

def conjugate(self) -> 'mpz':

120

"""Complex conjugate (returns self)."""

121

122

# Standard numeric methods

123

def __ceil__(self) -> 'mpz': ...

124

def __floor__(self) -> 'mpz': ...

125

def __round__(self, ndigits=None): ...

126

def __trunc__(self) -> 'mpz': ...

127

def __sizeof__(self) -> int: ...

128

```

129

130

### xmpz - Mutable Multiple-Precision Integer

131

132

Mutable version of mpz that allows in-place modifications. Useful for performance-critical code where creating new objects would be expensive.

133

134

```python { .api }

135

class xmpz(mpz):

136

def __init__(self, x=0, base=10):

137

"""Create mutable multiple-precision integer."""

138

139

# Mutable-specific methods

140

def copy(self) -> 'xmpz':

141

"""Create mutable copy."""

142

143

def make_mpz(self) -> mpz:

144

"""Convert to immutable mpz."""

145

146

# Bit iteration

147

def iter_bits(self, start: int = 0, stop: int = -1):

148

"""Iterator over bit positions that are set."""

149

150

def iter_clear(self, start: int = 0, stop: int = -1):

151

"""Iterator over bit positions that are clear."""

152

153

def iter_set(self, start: int = 0, stop: int = -1):

154

"""Iterator over bit positions that are set."""

155

156

# Low-level limb access

157

def num_limbs(self) -> int:

158

"""Number of limbs used internally."""

159

160

def limbs_read(self):

161

"""Read-only access to internal limbs."""

162

163

def limbs_write(self, n: int):

164

"""Writable access to n limbs."""

165

166

def limbs_modify(self, n: int):

167

"""Modify n limbs."""

168

169

def limbs_finish(self, n: int):

170

"""Finish limb modification."""

171

```

172

173

### mpq - Multiple-Precision Rational

174

175

Rational numbers with arbitrary-precision numerator and denominator. Automatically reduces fractions to lowest terms.

176

177

```python { .api }

178

class mpq:

179

def __init__(self, x=0, y=1):

180

"""

181

Create multiple-precision rational number.

182

183

Args:

184

x: Numerator (or single value to convert)

185

y: Denominator (ignored if x is already rational-like)

186

"""

187

188

# Properties

189

@property

190

def numerator(self) -> mpz:

191

"""Numerator as mpz."""

192

193

@property

194

def denominator(self) -> mpz:

195

"""Denominator as mpz."""

196

197

@property

198

def real(self) -> 'mpq':

199

"""Real part (returns self)."""

200

201

@property

202

def imag(self) -> mpz:

203

"""Imaginary part (returns 0)."""

204

205

# Conversion methods

206

def digits(self, base: int = 10, prec: int = 0) -> str:

207

"""String representation in specified base."""

208

209

def as_integer_ratio(self) -> tuple:

210

"""Return (numerator, denominator) as tuple of ints."""

211

212

@classmethod

213

def from_float(cls, x: float) -> 'mpq':

214

"""Create rational from float value."""

215

216

@classmethod

217

def from_decimal(cls, x) -> 'mpq':

218

"""Create rational from decimal.Decimal value."""

219

220

# Numeric methods

221

def __ceil__(self): ...

222

def __floor__(self): ...

223

def __round__(self, ndigits=None): ...

224

def __trunc__(self): ...

225

def __sizeof__(self) -> int: ...

226

def conjugate(self) -> 'mpq': ...

227

```

228

229

### mpfr - Multiple-Precision Floating Point

230

231

High-precision floating-point numbers based on the MPFR library with configurable precision and correct rounding.

232

233

```python { .api }

234

class mpfr:

235

def __init__(self, x=0.0, precision=None):

236

"""

237

Create multiple-precision floating-point number.

238

239

Args:

240

x: Initial value

241

precision: Precision in bits (None = use context precision)

242

"""

243

244

# Properties

245

@property

246

def precision(self) -> int:

247

"""Precision in bits."""

248

249

@property

250

def rc(self) -> int:

251

"""Return code from last operation."""

252

253

@property

254

def real(self) -> 'mpfr':

255

"""Real part (returns self)."""

256

257

@property

258

def imag(self) -> 'mpfr':

259

"""Imaginary part (returns mpfr(0))."""

260

261

# Predicates

262

def is_finite(self) -> bool:

263

"""Test if number is finite (not infinity or NaN)."""

264

265

def is_infinite(self) -> bool:

266

"""Test if number is infinite."""

267

268

def is_integer(self) -> bool:

269

"""Test if number represents an integer value."""

270

271

def is_nan(self) -> bool:

272

"""Test if number is NaN (Not a Number)."""

273

274

def is_regular(self) -> bool:

275

"""Test if number is regular (not zero, infinity, or NaN)."""

276

277

def is_signed(self) -> bool:

278

"""Test if number is negative (including -0)."""

279

280

def is_zero(self) -> bool:

281

"""Test if number is zero."""

282

283

# Conversion methods

284

def digits(self, base: int = 10, prec: int = 0) -> str:

285

"""String representation in specified base."""

286

287

def as_integer_ratio(self) -> tuple:

288

"""Return (numerator, denominator) as tuple."""

289

290

def as_mantissa_exp(self) -> tuple:

291

"""Return (mantissa, exponent) representation."""

292

293

def as_simple_fraction(self, max_denominator=None):

294

"""Convert to simple fraction representation."""

295

296

# Numeric methods

297

def __ceil__(self): ...

298

def __floor__(self): ...

299

def __round__(self, ndigits=None): ...

300

def __trunc__(self): ...

301

def __sizeof__(self) -> int: ...

302

def conjugate(self) -> 'mpfr': ...

303

```

304

305

### mpc - Multiple-Precision Complex

306

307

Complex numbers with arbitrary-precision real and imaginary parts based on the MPC library.

308

309

```python { .api }

310

class mpc:

311

def __init__(self, real=0, imag=0, precision=None):

312

"""

313

Create multiple-precision complex number.

314

315

Args:

316

real: Real part

317

imag: Imaginary part

318

precision: Precision in bits (tuple for separate real/imag precision)

319

"""

320

321

# Properties

322

@property

323

def precision(self) -> tuple:

324

"""Precision in bits as (real_precision, imag_precision)."""

325

326

@property

327

def rc(self) -> int:

328

"""Return code from last operation."""

329

330

@property

331

def real(self) -> mpfr:

332

"""Real part as mpfr."""

333

334

@property

335

def imag(self) -> mpfr:

336

"""Imaginary part as mpfr."""

337

338

# Predicates

339

def is_finite(self) -> bool:

340

"""Test if both real and imaginary parts are finite."""

341

342

def is_infinite(self) -> bool:

343

"""Test if either part is infinite."""

344

345

def is_nan(self) -> bool:

346

"""Test if either part is NaN."""

347

348

def is_zero(self) -> bool:

349

"""Test if number is zero."""

350

351

# Complex operations

352

def conjugate(self) -> 'mpc':

353

"""Return complex conjugate."""

354

355

# Conversion methods

356

def digits(self, base: int = 10, prec: int = 0) -> str:

357

"""String representation in specified base."""

358

359

def __complex__(self) -> complex:

360

"""Convert to Python complex (may lose precision)."""

361

362

# Numeric methods

363

def __sizeof__(self) -> int: ...

364

```

365

366

## Usage Examples

367

368

### Basic Operations

369

370

```python

371

import gmpy2

372

373

# Integer arithmetic

374

a = gmpy2.mpz("12345678901234567890")

375

b = gmpy2.mpz("98765432109876543210")

376

print(a + b) # Arbitrary precision addition

377

378

# Rational arithmetic

379

x = gmpy2.mpq(22, 7) # 22/7 approximation of pi

380

y = gmpy2.mpq(355, 113) # Better approximation

381

print(x * y) # Exact rational multiplication

382

383

# High-precision floating-point

384

with gmpy2.local_context(precision=100):

385

z = gmpy2.mpfr("1.23456789012345678901234567890")

386

print(gmpy2.sqrt(z)) # 100-bit precision square root

387

388

# Complex numbers

389

c = gmpy2.mpc("3.14159+2.71828j")

390

print(c.conjugate()) # Complex conjugate

391

```

392

393

### Type Conversion

394

395

```python

396

# Convert between types

397

integer = gmpy2.mpz(42)

398

rational = gmpy2.mpq(integer) # 42/1

399

real = gmpy2.mpfr(rational) # 42.0

400

complex_num = gmpy2.mpc(real) # 42.0+0.0j

401

402

# From Python types

403

from fractions import Fraction

404

from decimal import Decimal

405

406

rat_from_frac = gmpy2.mpq(Fraction(22, 7))

407

rat_from_dec = gmpy2.mpq.from_decimal(Decimal("3.14159"))

408

```