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

arithmetic.mddocs/

0

# Arithmetic Operations

1

2

gmpy2 provides comprehensive arithmetic operations that work with all multiple-precision types. Operations automatically promote types and use the current context for precision and rounding control.

3

4

## Capabilities

5

6

### Basic Arithmetic

7

8

Fundamental arithmetic operations with context-aware precision and rounding.

9

10

```python { .api }

11

def add(x, y):

12

"""

13

Add two numbers using current context.

14

15

Args:

16

x, y: Numeric values (int, float, mpz, mpq, mpfr, mpc, etc.)

17

18

Returns:

19

Result promoted to appropriate gmpy2 type

20

"""

21

22

def sub(x, y):

23

"""

24

Subtract y from x using current context.

25

26

Args:

27

x, y: Numeric values

28

29

Returns:

30

Result promoted to appropriate gmpy2 type

31

"""

32

33

def mul(x, y):

34

"""

35

Multiply two numbers using current context.

36

37

Args:

38

x, y: Numeric values

39

40

Returns:

41

Result promoted to appropriate gmpy2 type

42

"""

43

44

def div(x, y):

45

"""

46

Divide x by y using current context.

47

48

Args:

49

x, y: Numeric values

50

51

Returns:

52

Result promoted to appropriate gmpy2 type

53

"""

54

55

def square(x):

56

"""

57

Square a number using current context.

58

59

Args:

60

x: Numeric value

61

62

Returns:

63

x squared, promoted to appropriate gmpy2 type

64

"""

65

```

66

67

### Division Operations

68

69

Multiple division modes for precise control over rounding behavior.

70

71

```python { .api }

72

def floor_div(x, y):

73

"""Floor division (towards negative infinity)."""

74

75

def divexact(x, y):

76

"""

77

Exact division for integers (assumes y divides x exactly).

78

79

Args:

80

x, y: Integer values

81

82

Returns:

83

mpz result of x / y

84

85

Note:

86

Faster than regular division when exact division is guaranteed

87

"""

88

89

# Ceiling division

90

def c_div(x, y):

91

"""Ceiling division (towards positive infinity)."""

92

93

def c_divmod(x, y):

94

"""Ceiling division with remainder."""

95

96

def c_mod(x, y):

97

"""Ceiling modulo."""

98

99

# Floor division

100

def f_div(x, y):

101

"""Floor division (towards negative infinity)."""

102

103

def f_divmod(x, y):

104

"""Floor division with remainder."""

105

106

def f_mod(x, y):

107

"""Floor modulo."""

108

109

# Truncating division

110

def t_div(x, y):

111

"""Truncating division (towards zero)."""

112

113

def t_divmod(x, y):

114

"""Truncating division with remainder."""

115

116

def t_mod(x, y):

117

"""Truncating modulo."""

118

```

119

120

### Division by Powers of 2

121

122

Optimized division operations for powers of 2.

123

124

```python { .api }

125

# Ceiling division by 2^n

126

def c_div_2exp(x, n):

127

"""Ceiling division by 2^n."""

128

129

def c_divmod_2exp(x, n):

130

"""Ceiling division by 2^n with remainder."""

131

132

def c_mod_2exp(x, n):

133

"""Ceiling modulo 2^n."""

134

135

# Floor division by 2^n

136

def f_div_2exp(x, n):

137

"""Floor division by 2^n."""

138

139

def f_divmod_2exp(x, n):

140

"""Floor division by 2^n with remainder."""

141

142

def f_mod_2exp(x, n):

143

"""Floor modulo 2^n."""

144

145

# Truncating division by 2^n

146

def t_div_2exp(x, n):

147

"""Truncating division by 2^n."""

148

149

def t_divmod_2exp(x, n):

150

"""Truncating division by 2^n with remainder."""

151

152

def t_mod_2exp(x, n):

153

"""Truncating modulo 2^n."""

154

155

# Multiplication/division by powers of 2

156

def mul_2exp(x, n):

157

"""Multiply by 2^n (left shift)."""

158

159

def div_2exp(x, n):

160

"""Divide by 2^n (right shift)."""

161

```

162

163

### Modular Arithmetic

164

165

Power operations with modular arithmetic for cryptographic applications.

166

167

```python { .api }

168

def powmod(x, y, z):

169

"""

170

Compute (x^y) mod z efficiently.

171

172

Args:

173

x: Base

174

y: Exponent

175

z: Modulus

176

177

Returns:

178

mpz result of (x^y) mod z

179

180

Note:

181

Much faster than pow(x, y) % z for large numbers

182

"""

183

184

def powmod_sec(x, y, z):

185

"""

186

Secure modular exponentiation resistant to timing attacks.

187

188

Args:

189

x: Base

190

y: Exponent

191

z: Modulus

192

193

Returns:

194

mpz result of (x^y) mod z

195

196

Note:

197

Uses constant-time algorithm suitable for cryptographic use

198

"""

199

200

def powmod_base_list(bases, exp, mod):

201

"""

202

Compute product of (base^exp) mod mod for multiple bases.

203

204

Args:

205

bases: List of base values

206

exp: Common exponent

207

mod: Modulus

208

209

Returns:

210

mpz result

211

"""

212

213

def powmod_exp_list(base, exps, mod):

214

"""

215

Compute product of (base^exp) mod mod for multiple exponents.

216

217

Args:

218

base: Common base

219

exps: List of exponents

220

mod: Modulus

221

222

Returns:

223

mpz result

224

"""

225

```

226

227

### Modulo Operations

228

229

Standard modulo operations with different rounding modes.

230

231

```python { .api }

232

def mod(x, y):

233

"""

234

Compute x mod y using current context.

235

236

Args:

237

x, y: Numeric values

238

239

Returns:

240

Remainder of x / y

241

"""

242

```

243

244

### Rational Arithmetic

245

246

Specialized operations for rational numbers.

247

248

```python { .api }

249

def qdiv(x, y):

250

"""

251

Rational division returning exact mpq result.

252

253

Args:

254

x, y: Numeric values

255

256

Returns:

257

mpq representing exact x / y

258

"""

259

260

def numer(x):

261

"""

262

Get numerator of rational number.

263

264

Args:

265

x: Rational or integer value

266

267

Returns:

268

mpz numerator

269

"""

270

271

def denom(x):

272

"""

273

Get denominator of rational number.

274

275

Args:

276

x: Rational or integer value

277

278

Returns:

279

mpz denominator (1 for integers)

280

"""

281

```

282

283

### Utility Functions

284

285

Comparison and utility operations.

286

287

```python { .api }

288

def cmp(x, y):

289

"""

290

Three-way comparison.

291

292

Args:

293

x, y: Numeric values

294

295

Returns:

296

-1 if x < y, 0 if x == y, 1 if x > y

297

"""

298

299

def cmp_abs(x, y):

300

"""

301

Compare absolute values.

302

303

Args:

304

x, y: Numeric values

305

306

Returns:

307

-1 if |x| < |y|, 0 if |x| == |y|, 1 if |x| > |y|

308

"""

309

310

def sign(x):

311

"""

312

Sign of number.

313

314

Args:

315

x: Numeric value

316

317

Returns:

318

-1 for negative, 0 for zero, 1 for positive

319

"""

320

321

def copy_sign(x, y):

322

"""

323

Copy sign from y to magnitude of x.

324

325

Args:

326

x: Value providing magnitude

327

y: Value providing sign

328

329

Returns:

330

Value with magnitude of x and sign of y

331

"""

332

```

333

334

## Usage Examples

335

336

### Basic Arithmetic with Context

337

338

```python

339

import gmpy2

340

341

# Default precision arithmetic

342

a = gmpy2.mpfr("1.23456789")

343

b = gmpy2.mpfr("9.87654321")

344

print(gmpy2.add(a, b)) # Uses default precision

345

346

# High precision arithmetic

347

with gmpy2.local_context(precision=100):

348

x = gmpy2.mpfr("1.23456789012345678901234567890")

349

y = gmpy2.mpfr("9.87654321098765432109876543210")

350

result = gmpy2.add(x, y) # 100-bit precision

351

print(result)

352

```

353

354

### Modular Arithmetic

355

356

```python

357

import gmpy2

358

359

# Large number modular exponentiation

360

base = gmpy2.mpz("12345678901234567890")

361

exp = gmpy2.mpz("98765432109876543210")

362

mod = gmpy2.mpz("1000000007")

363

364

# Efficient modular exponentiation

365

result = gmpy2.powmod(base, exp, mod)

366

print(result)

367

368

# Cryptographic secure version

369

secure_result = gmpy2.powmod_sec(base, exp, mod)

370

print(secure_result)

371

```

372

373

### Division Modes

374

375

```python

376

import gmpy2

377

378

x = gmpy2.mpz(17)

379

y = gmpy2.mpz(5)

380

381

# Different division modes

382

print(gmpy2.f_div(x, y)) # Floor: 3

383

print(gmpy2.c_div(x, y)) # Ceiling: 4

384

print(gmpy2.t_div(x, y)) # Truncate: 3

385

386

print(gmpy2.f_mod(x, y)) # Floor mod: 2

387

print(gmpy2.c_mod(x, y)) # Ceiling mod: -3

388

print(gmpy2.t_mod(x, y)) # Truncate mod: 2

389

```

390

391

### Rational Arithmetic

392

393

```python

394

import gmpy2

395

396

# Exact rational arithmetic

397

a = gmpy2.mpq(22, 7) # 22/7

398

b = gmpy2.mpq(355, 113) # 355/113

399

400

# Exact operations

401

sum_exact = gmpy2.add(a, b) # Returns mpq

402

print(f"Sum: {sum_exact}")

403

print(f"Numerator: {gmpy2.numer(sum_exact)}")

404

print(f"Denominator: {gmpy2.denom(sum_exact)}")

405

406

# Rational division

407

quotient = gmpy2.qdiv(a, b)

408

print(f"Quotient: {quotient}")

409

```