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

math-functions.mddocs/

0

# Mathematical Functions

1

2

gmpy2 provides an extensive collection of mathematical functions with arbitrary precision, including trigonometric, logarithmic, exponential, special functions, and mathematical constants. All functions respect the current context settings for precision and rounding.

3

4

## Capabilities

5

6

### Trigonometric Functions

7

8

Standard trigonometric functions with high precision.

9

10

```python { .api }

11

def sin(x):

12

"""

13

Sine function.

14

15

Args:

16

x: Angle in radians (numeric type)

17

18

Returns:

19

Result using current context precision and rounding

20

"""

21

22

def cos(x):

23

"""

24

Cosine function.

25

26

Args:

27

x: Angle in radians (numeric type)

28

29

Returns:

30

Result using current context precision and rounding

31

"""

32

33

def tan(x):

34

"""

35

Tangent function.

36

37

Args:

38

x: Angle in radians (numeric type)

39

40

Returns:

41

Result using current context precision and rounding

42

"""

43

44

def sin_cos(x):

45

"""

46

Compute sine and cosine simultaneously.

47

48

Args:

49

x: Angle in radians (numeric type)

50

51

Returns:

52

tuple: (sin(x), cos(x))

53

54

Note:

55

More efficient than computing separately

56

"""

57

```

58

59

### Inverse Trigonometric Functions

60

61

```python { .api }

62

def asin(x):

63

"""

64

Arcsine function.

65

66

Args:

67

x: Value in range [-1, 1]

68

69

Returns:

70

Angle in radians in range [-π/2, π/2]

71

"""

72

73

def acos(x):

74

"""

75

Arccosine function.

76

77

Args:

78

x: Value in range [-1, 1]

79

80

Returns:

81

Angle in radians in range [0, π]

82

"""

83

84

def atan(x):

85

"""

86

Arctangent function.

87

88

Args:

89

x: Numeric value

90

91

Returns:

92

Angle in radians in range (-π/2, π/2)

93

"""

94

95

def atan2(y, x):

96

"""

97

Two-argument arctangent function.

98

99

Args:

100

y: y-coordinate

101

x: x-coordinate

102

103

Returns:

104

Angle in radians in range (-π, π]

105

106

Note:

107

Properly handles all quadrants and special cases

108

"""

109

```

110

111

### Hyperbolic Functions

112

113

```python { .api }

114

def sinh(x):

115

"""Hyperbolic sine function."""

116

117

def cosh(x):

118

"""Hyperbolic cosine function."""

119

120

def tanh(x):

121

"""Hyperbolic tangent function."""

122

123

def sinh_cosh(x):

124

"""

125

Compute hyperbolic sine and cosine simultaneously.

126

127

Returns:

128

tuple: (sinh(x), cosh(x))

129

"""

130

131

def asinh(x):

132

"""Inverse hyperbolic sine function."""

133

134

def acosh(x):

135

"""

136

Inverse hyperbolic cosine function.

137

138

Args:

139

x: Value >= 1

140

"""

141

142

def atanh(x):

143

"""

144

Inverse hyperbolic tangent function.

145

146

Args:

147

x: Value in range (-1, 1)

148

"""

149

```

150

151

### Additional Trigonometric Functions

152

153

```python { .api }

154

def cot(x):

155

"""Cotangent function (1/tan(x))."""

156

157

def coth(x):

158

"""Hyperbolic cotangent function."""

159

160

def sec(x):

161

"""Secant function (1/cos(x))."""

162

163

def sech(x):

164

"""Hyperbolic secant function."""

165

166

def csc(x):

167

"""Cosecant function (1/sin(x))."""

168

169

def csch(x):

170

"""Hyperbolic cosecant function."""

171

```

172

173

### Exponential and Logarithmic Functions

174

175

```python { .api }

176

def exp(x):

177

"""

178

Exponential function e^x.

179

180

Args:

181

x: Numeric value

182

183

Returns:

184

e raised to the power x

185

"""

186

187

def exp2(x):

188

"""

189

Base-2 exponential function 2^x.

190

191

Args:

192

x: Numeric value

193

194

Returns:

195

2 raised to the power x

196

"""

197

198

def exp10(x):

199

"""

200

Base-10 exponential function 10^x.

201

202

Args:

203

x: Numeric value

204

205

Returns:

206

10 raised to the power x

207

"""

208

209

def expm1(x):

210

"""

211

Compute exp(x) - 1 accurately for small x.

212

213

Args:

214

x: Numeric value (typically small)

215

216

Returns:

217

exp(x) - 1

218

219

Note:

220

More accurate than exp(x) - 1 when x is close to zero

221

"""

222

223

def log(x):

224

"""

225

Natural logarithm (base e).

226

227

Args:

228

x: Positive numeric value

229

230

Returns:

231

Natural logarithm of x

232

"""

233

234

def log2(x):

235

"""

236

Base-2 logarithm.

237

238

Args:

239

x: Positive numeric value

240

241

Returns:

242

Base-2 logarithm of x

243

"""

244

245

def log10(x):

246

"""

247

Base-10 logarithm.

248

249

Args:

250

x: Positive numeric value

251

252

Returns:

253

Base-10 logarithm of x

254

"""

255

256

def log1p(x):

257

"""

258

Compute log(1 + x) accurately for small x.

259

260

Args:

261

x: Numeric value > -1

262

263

Returns:

264

log(1 + x)

265

266

Note:

267

More accurate than log(1 + x) when x is close to zero

268

"""

269

```

270

271

### Power and Root Functions

272

273

```python { .api }

274

def sqrt(x):

275

"""

276

Square root function.

277

278

Args:

279

x: Non-negative numeric value

280

281

Returns:

282

Square root of x

283

"""

284

285

def rec_sqrt(x):

286

"""

287

Reciprocal square root (1/sqrt(x)).

288

289

Args:

290

x: Positive numeric value

291

292

Returns:

293

1 / sqrt(x)

294

"""

295

296

def cbrt(x):

297

"""

298

Cube root function.

299

300

Args:

301

x: Numeric value

302

303

Returns:

304

Cube root of x

305

"""

306

307

def root(x, n):

308

"""

309

nth root function.

310

311

Args:

312

x: Numeric value

313

n: Positive integer root

314

315

Returns:

316

nth root of x

317

"""

318

319

def rootn(x, n):

320

"""

321

nth root function (alias for root).

322

323

Args:

324

x: Numeric value

325

n: Positive integer root

326

327

Returns:

328

nth root of x

329

"""

330

```

331

332

### Rounding and Truncation Functions

333

334

```python { .api }

335

def ceil(x):

336

"""

337

Ceiling function (round toward positive infinity).

338

339

Args:

340

x: Numeric value

341

342

Returns:

343

Smallest integer >= x

344

"""

345

346

def floor(x):

347

"""

348

Floor function (round toward negative infinity).

349

350

Args:

351

x: Numeric value

352

353

Returns:

354

Largest integer <= x

355

"""

356

357

def trunc(x):

358

"""

359

Truncation function (round toward zero).

360

361

Args:

362

x: Numeric value

363

364

Returns:

365

Integer part of x

366

"""

367

368

def rint(x):

369

"""

370

Round to nearest integer using current rounding mode.

371

372

Args:

373

x: Numeric value

374

375

Returns:

376

Rounded value

377

"""

378

379

def rint_ceil(x):

380

"""Round to nearest integer, ties toward positive infinity."""

381

382

def rint_floor(x):

383

"""Round to nearest integer, ties toward negative infinity."""

384

385

def rint_round(x):

386

"""Round to nearest integer, ties away from zero."""

387

388

def rint_trunc(x):

389

"""Round to nearest integer, ties toward zero."""

390

391

def round2(x, n):

392

"""

393

Round to n binary digits.

394

395

Args:

396

x: Numeric value

397

n: Number of binary digits

398

399

Returns:

400

Rounded value

401

"""

402

403

def round_away(x):

404

"""Round away from zero."""

405

```

406

407

### Special Functions

408

409

```python { .api }

410

def gamma(x):

411

"""

412

Gamma function Γ(x).

413

414

Args:

415

x: Numeric value (x > 0 for real results)

416

417

Returns:

418

Γ(x) = ∫₀^∞ t^(x-1) e^(-t) dt

419

"""

420

421

def gamma_inc(x, y):

422

"""

423

Incomplete gamma function.

424

425

Args:

426

x: Parameter

427

y: Upper limit

428

429

Returns:

430

Incomplete gamma function value

431

"""

432

433

def lgamma(x):

434

"""

435

Natural logarithm of absolute value of gamma function.

436

437

Args:

438

x: Numeric value

439

440

Returns:

441

log(|Γ(x)|)

442

"""

443

444

def lngamma(x):

445

"""Alias for lgamma."""

446

447

def digamma(x):

448

"""

449

Digamma function (logarithmic derivative of gamma).

450

451

Args:

452

x: Numeric value

453

454

Returns:

455

ψ(x) = Γ'(x) / Γ(x)

456

"""

457

458

def factorial(x):

459

"""

460

Factorial function (uses gamma for non-integers).

461

462

Args:

463

x: Non-negative numeric value

464

465

Returns:

466

x! = Γ(x + 1)

467

"""

468

469

def erf(x):

470

"""

471

Error function.

472

473

Args:

474

x: Numeric value

475

476

Returns:

477

erf(x) = (2/√π) ∫₀^x e^(-t²) dt

478

"""

479

480

def erfc(x):

481

"""

482

Complementary error function.

483

484

Args:

485

x: Numeric value

486

487

Returns:

488

erfc(x) = 1 - erf(x)

489

"""

490

491

def zeta(x):

492

"""

493

Riemann zeta function.

494

495

Args:

496

x: Numeric value

497

498

Returns:

499

ζ(x) = Σ(n=1 to ∞) 1/n^x

500

"""

501

502

def ai(x):

503

"""

504

Airy function Ai(x).

505

506

Args:

507

x: Numeric value

508

509

Returns:

510

Airy function of the first kind

511

"""

512

513

def eint(x):

514

"""

515

Exponential integral.

516

517

Args:

518

x: Numeric value

519

520

Returns:

521

Exponential integral Ei(x)

522

"""

523

524

def li2(x):

525

"""

526

Dilogarithm function.

527

528

Args:

529

x: Numeric value

530

531

Returns:

532

Li₂(x) = -∫₀^x log(1-t)/t dt

533

"""

534

```

535

536

### Bessel Functions

537

538

```python { .api }

539

def j0(x):

540

"""Bessel function of the first kind, order 0."""

541

542

def j1(x):

543

"""Bessel function of the first kind, order 1."""

544

545

def jn(n, x):

546

"""

547

Bessel function of the first kind, order n.

548

549

Args:

550

n: Order (integer)

551

x: Argument

552

"""

553

554

def y0(x):

555

"""Bessel function of the second kind, order 0."""

556

557

def y1(x):

558

"""Bessel function of the second kind, order 1."""

559

560

def yn(n, x):

561

"""

562

Bessel function of the second kind, order n.

563

564

Args:

565

n: Order (integer)

566

x: Argument

567

"""

568

```

569

570

### Utility Functions

571

572

```python { .api }

573

def degrees(x):

574

"""

575

Convert radians to degrees.

576

577

Args:

578

x: Angle in radians

579

580

Returns:

581

Angle in degrees

582

"""

583

584

def radians(x):

585

"""

586

Convert degrees to radians.

587

588

Args:

589

x: Angle in degrees

590

591

Returns:

592

Angle in radians

593

"""

594

595

def hypot(x, y):

596

"""

597

Euclidean distance sqrt(x² + y²).

598

599

Args:

600

x, y: Numeric values

601

602

Returns:

603

sqrt(x² + y²)

604

605

Note:

606

Avoids overflow/underflow for large/small values

607

"""

608

609

def remainder(x, y):

610

"""

611

IEEE remainder of x / y.

612

613

Args:

614

x, y: Numeric values

615

616

Returns:

617

IEEE remainder

618

"""

619

620

def remquo(x, y):

621

"""

622

IEEE remainder and quotient.

623

624

Args:

625

x, y: Numeric values

626

627

Returns:

628

tuple: (remainder, quotient)

629

"""

630

631

def fmod(x, y):

632

"""

633

Floating-point remainder of x / y.

634

635

Args:

636

x, y: Numeric values

637

638

Returns:

639

Remainder with same sign as x

640

"""

641

642

def modf(x):

643

"""

644

Split into integer and fractional parts.

645

646

Args:

647

x: Numeric value

648

649

Returns:

650

tuple: (fractional_part, integer_part)

651

"""

652

653

def frexp(x):

654

"""

655

Extract mantissa and exponent.

656

657

Args:

658

x: Numeric value

659

660

Returns:

661

tuple: (mantissa, exponent) where x = mantissa * 2^exponent

662

"""

663

664

def agm(x, y):

665

"""

666

Arithmetic-geometric mean.

667

668

Args:

669

x, y: Positive numeric values

670

671

Returns:

672

Arithmetic-geometric mean of x and y

673

"""

674

675

def fsum(iterable):

676

"""

677

Accurate floating-point sum.

678

679

Args:

680

iterable: Sequence of numeric values

681

682

Returns:

683

Accurate sum using current precision

684

685

Note:

686

More accurate than built-in sum() for floating-point

687

"""

688

```

689

690

### Fused Multiply-Add Operations

691

692

```python { .api }

693

def fma(x, y, z):

694

"""

695

Fused multiply-add: (x * y) + z.

696

697

Args:

698

x, y, z: Numeric values

699

700

Returns:

701

(x * y) + z computed with single rounding

702

"""

703

704

def fms(x, y, z):

705

"""

706

Fused multiply-subtract: (x * y) - z.

707

708

Args:

709

x, y, z: Numeric values

710

711

Returns:

712

(x * y) - z computed with single rounding

713

"""

714

715

def fmma(x, y, z, w):

716

"""

717

Fused multiply-multiply-add: (x * y) + (z * w).

718

719

Args:

720

x, y, z, w: Numeric values

721

722

Returns:

723

(x * y) + (z * w) computed with single rounding

724

"""

725

726

def fmms(x, y, z, w):

727

"""

728

Fused multiply-multiply-subtract: (x * y) - (z * w).

729

730

Args:

731

x, y, z, w: Numeric values

732

733

Returns:

734

(x * y) - (z * w) computed with single rounding

735

"""

736

```

737

738

### Min/Max Functions

739

740

```python { .api }

741

def maxnum(x, y):

742

"""

743

Maximum of two numbers (NaN-aware).

744

745

Args:

746

x, y: Numeric values

747

748

Returns:

749

Maximum value, treating NaN specially

750

"""

751

752

def minnum(x, y):

753

"""

754

Minimum of two numbers (NaN-aware).

755

756

Args:

757

x, y: Numeric values

758

759

Returns:

760

Minimum value, treating NaN specially

761

"""

762

```

763

764

### Complex Functions

765

766

```python { .api }

767

def norm(x):

768

"""

769

Complex norm (squared magnitude).

770

771

Args:

772

x: Complex number

773

774

Returns:

775

|x|² = real(x)² + imag(x)²

776

"""

777

778

def phase(x):

779

"""

780

Complex phase (argument).

781

782

Args:

783

x: Complex number

784

785

Returns:

786

Phase angle in radians

787

"""

788

789

def polar(x):

790

"""

791

Convert to polar form.

792

793

Args:

794

x: Complex number

795

796

Returns:

797

tuple: (magnitude, phase)

798

"""

799

800

def proj(x):

801

"""

802

Riemann sphere projection.

803

804

Args:

805

x: Complex number

806

807

Returns:

808

Projection onto Riemann sphere

809

"""

810

811

def rect(r, theta):

812

"""

813

Convert from polar to rectangular form.

814

815

Args:

816

r: Magnitude

817

theta: Phase angle in radians

818

819

Returns:

820

Complex number r * e^(i*theta)

821

"""

822

823

def root_of_unity(n, k):

824

"""

825

nth root of unity.

826

827

Args:

828

n: Order

829

k: Index (0 <= k < n)

830

831

Returns:

832

e^(2πik/n)

833

"""

834

```

835

836

### Mathematical Constants

837

838

```python { .api }

839

def const_pi(precision=None):

840

"""

841

Pi constant.

842

843

Args:

844

precision: Precision in bits (None = use context)

845

846

Returns:

847

π with specified precision

848

"""

849

850

def const_euler(precision=None):

851

"""

852

Euler's constant (gamma).

853

854

Args:

855

precision: Precision in bits (None = use context)

856

857

Returns:

858

Euler-Mascheroni constant γ

859

"""

860

861

def const_catalan(precision=None):

862

"""

863

Catalan's constant.

864

865

Args:

866

precision: Precision in bits (None = use context)

867

868

Returns:

869

Catalan's constant G

870

"""

871

872

def const_log2(precision=None):

873

"""

874

Natural logarithm of 2.

875

876

Args:

877

precision: Precision in bits (None = use context)

878

879

Returns:

880

ln(2) with specified precision

881

"""

882

```

883

884

## Usage Examples

885

886

### High-Precision Trigonometry

887

888

```python

889

import gmpy2

890

891

# Set high precision for calculations

892

with gmpy2.local_context(precision=100):

893

# High-precision sine and cosine

894

x = gmpy2.const_pi() / 4 # π/4

895

sin_val = gmpy2.sin(x)

896

cos_val = gmpy2.cos(x)

897

898

print(f"sin(π/4) = {sin_val}")

899

print(f"cos(π/4) = {cos_val}")

900

901

# Verify sin²(x) + cos²(x) = 1

902

identity = sin_val**2 + cos_val**2

903

print(f"sin²(π/4) + cos²(π/4) = {identity}")

904

905

# More efficient simultaneous calculation

906

sin_cos_vals = gmpy2.sin_cos(x)

907

print(f"sin_cos(π/4) = {sin_cos_vals}")

908

```

909

910

### Exponential and Logarithmic Functions

911

912

```python

913

import gmpy2

914

915

with gmpy2.local_context(precision=80):

916

# Natural exponential and logarithm

917

x = gmpy2.mpfr("2.5")

918

exp_x = gmpy2.exp(x)

919

log_exp_x = gmpy2.log(exp_x)

920

921

print(f"exp({x}) = {exp_x}")

922

print(f"log(exp({x})) = {log_exp_x}")

923

924

# Small value accuracy

925

small_x = gmpy2.mpfr("1e-10")

926

exp_m1_direct = gmpy2.exp(small_x) - 1

927

exp_m1_accurate = gmpy2.expm1(small_x)

928

929

print(f"exp({small_x}) - 1 (direct) = {exp_m1_direct}")

930

print(f"expm1({small_x}) = {exp_m1_accurate}")

931

```

932

933

### Special Functions

934

935

```python

936

import gmpy2

937

938

with gmpy2.local_context(precision=60):

939

# Gamma function

940

x = gmpy2.mpfr("5.5")

941

gamma_x = gmpy2.gamma(x)

942

factorial_equivalent = gmpy2.factorial(x - 1)

943

944

print(f"Γ({x}) = {gamma_x}")

945

print(f"({x-1})! = {factorial_equivalent}")

946

947

# Error function

948

z = gmpy2.mpfr("1.0")

949

erf_z = gmpy2.erf(z)

950

erfc_z = gmpy2.erfc(z)

951

952

print(f"erf({z}) = {erf_z}")

953

print(f"erfc({z}) = {erfc_z}")

954

print(f"erf + erfc = {erf_z + erfc_z}") # Should be 1

955

```

956

957

### Mathematical Constants

958

959

```python

960

import gmpy2

961

962

# Compare constants at different precisions

963

precisions = [50, 100, 200]

964

965

for prec in precisions:

966

with gmpy2.local_context(precision=prec):

967

pi_val = gmpy2.const_pi()

968

e_val = gmpy2.exp(1)

969

euler_gamma = gmpy2.const_euler()

970

971

print(f"\nPrecision: {prec} bits")

972

print(f"π = {pi_val}")

973

print(f"e = {e_val}")

974

print(f"γ = {euler_gamma}")

975

```

976

977

### Complex Mathematical Functions

978

979

```python

980

import gmpy2

981

982

with gmpy2.local_context(precision=80):

983

# Complex number operations

984

z = gmpy2.mpc("1+2j")

985

986

# Complex exponential

987

exp_z = gmpy2.exp(z)

988

print(f"exp({z}) = {exp_z}")

989

990

# Complex logarithm

991

log_z = gmpy2.log(z)

992

print(f"log({z}) = {log_z}")

993

994

# Polar form

995

magnitude, phase_angle = gmpy2.polar(z)

996

print(f"Polar form: magnitude={magnitude}, phase={phase_angle}")

997

998

# Convert back to rectangular

999

rect_z = gmpy2.rect(magnitude, phase_angle)

1000

print(f"Back to rectangular: {rect_z}")

1001

```