Multiple-precision arithmetic library providing fast GMP, MPFR, and MPC interfaces for Python
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
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.
Standard trigonometric functions with high precision.
def sin(x):
"""
Sine function.
Args:
x: Angle in radians (numeric type)
Returns:
Result using current context precision and rounding
"""
def cos(x):
"""
Cosine function.
Args:
x: Angle in radians (numeric type)
Returns:
Result using current context precision and rounding
"""
def tan(x):
"""
Tangent function.
Args:
x: Angle in radians (numeric type)
Returns:
Result using current context precision and rounding
"""
def sin_cos(x):
"""
Compute sine and cosine simultaneously.
Args:
x: Angle in radians (numeric type)
Returns:
tuple: (sin(x), cos(x))
Note:
More efficient than computing separately
"""def asin(x):
"""
Arcsine function.
Args:
x: Value in range [-1, 1]
Returns:
Angle in radians in range [-π/2, π/2]
"""
def acos(x):
"""
Arccosine function.
Args:
x: Value in range [-1, 1]
Returns:
Angle in radians in range [0, π]
"""
def atan(x):
"""
Arctangent function.
Args:
x: Numeric value
Returns:
Angle in radians in range (-π/2, π/2)
"""
def atan2(y, x):
"""
Two-argument arctangent function.
Args:
y: y-coordinate
x: x-coordinate
Returns:
Angle in radians in range (-π, π]
Note:
Properly handles all quadrants and special cases
"""def sinh(x):
"""Hyperbolic sine function."""
def cosh(x):
"""Hyperbolic cosine function."""
def tanh(x):
"""Hyperbolic tangent function."""
def sinh_cosh(x):
"""
Compute hyperbolic sine and cosine simultaneously.
Returns:
tuple: (sinh(x), cosh(x))
"""
def asinh(x):
"""Inverse hyperbolic sine function."""
def acosh(x):
"""
Inverse hyperbolic cosine function.
Args:
x: Value >= 1
"""
def atanh(x):
"""
Inverse hyperbolic tangent function.
Args:
x: Value in range (-1, 1)
"""def cot(x):
"""Cotangent function (1/tan(x))."""
def coth(x):
"""Hyperbolic cotangent function."""
def sec(x):
"""Secant function (1/cos(x))."""
def sech(x):
"""Hyperbolic secant function."""
def csc(x):
"""Cosecant function (1/sin(x))."""
def csch(x):
"""Hyperbolic cosecant function."""def exp(x):
"""
Exponential function e^x.
Args:
x: Numeric value
Returns:
e raised to the power x
"""
def exp2(x):
"""
Base-2 exponential function 2^x.
Args:
x: Numeric value
Returns:
2 raised to the power x
"""
def exp10(x):
"""
Base-10 exponential function 10^x.
Args:
x: Numeric value
Returns:
10 raised to the power x
"""
def expm1(x):
"""
Compute exp(x) - 1 accurately for small x.
Args:
x: Numeric value (typically small)
Returns:
exp(x) - 1
Note:
More accurate than exp(x) - 1 when x is close to zero
"""
def log(x):
"""
Natural logarithm (base e).
Args:
x: Positive numeric value
Returns:
Natural logarithm of x
"""
def log2(x):
"""
Base-2 logarithm.
Args:
x: Positive numeric value
Returns:
Base-2 logarithm of x
"""
def log10(x):
"""
Base-10 logarithm.
Args:
x: Positive numeric value
Returns:
Base-10 logarithm of x
"""
def log1p(x):
"""
Compute log(1 + x) accurately for small x.
Args:
x: Numeric value > -1
Returns:
log(1 + x)
Note:
More accurate than log(1 + x) when x is close to zero
"""def sqrt(x):
"""
Square root function.
Args:
x: Non-negative numeric value
Returns:
Square root of x
"""
def rec_sqrt(x):
"""
Reciprocal square root (1/sqrt(x)).
Args:
x: Positive numeric value
Returns:
1 / sqrt(x)
"""
def cbrt(x):
"""
Cube root function.
Args:
x: Numeric value
Returns:
Cube root of x
"""
def root(x, n):
"""
nth root function.
Args:
x: Numeric value
n: Positive integer root
Returns:
nth root of x
"""
def rootn(x, n):
"""
nth root function (alias for root).
Args:
x: Numeric value
n: Positive integer root
Returns:
nth root of x
"""def ceil(x):
"""
Ceiling function (round toward positive infinity).
Args:
x: Numeric value
Returns:
Smallest integer >= x
"""
def floor(x):
"""
Floor function (round toward negative infinity).
Args:
x: Numeric value
Returns:
Largest integer <= x
"""
def trunc(x):
"""
Truncation function (round toward zero).
Args:
x: Numeric value
Returns:
Integer part of x
"""
def rint(x):
"""
Round to nearest integer using current rounding mode.
Args:
x: Numeric value
Returns:
Rounded value
"""
def rint_ceil(x):
"""Round to nearest integer, ties toward positive infinity."""
def rint_floor(x):
"""Round to nearest integer, ties toward negative infinity."""
def rint_round(x):
"""Round to nearest integer, ties away from zero."""
def rint_trunc(x):
"""Round to nearest integer, ties toward zero."""
def round2(x, n):
"""
Round to n binary digits.
Args:
x: Numeric value
n: Number of binary digits
Returns:
Rounded value
"""
def round_away(x):
"""Round away from zero."""def gamma(x):
"""
Gamma function Γ(x).
Args:
x: Numeric value (x > 0 for real results)
Returns:
Γ(x) = ∫₀^∞ t^(x-1) e^(-t) dt
"""
def gamma_inc(x, y):
"""
Incomplete gamma function.
Args:
x: Parameter
y: Upper limit
Returns:
Incomplete gamma function value
"""
def lgamma(x):
"""
Natural logarithm of absolute value of gamma function.
Args:
x: Numeric value
Returns:
log(|Γ(x)|)
"""
def lngamma(x):
"""Alias for lgamma."""
def digamma(x):
"""
Digamma function (logarithmic derivative of gamma).
Args:
x: Numeric value
Returns:
ψ(x) = Γ'(x) / Γ(x)
"""
def factorial(x):
"""
Factorial function (uses gamma for non-integers).
Args:
x: Non-negative numeric value
Returns:
x! = Γ(x + 1)
"""
def erf(x):
"""
Error function.
Args:
x: Numeric value
Returns:
erf(x) = (2/√π) ∫₀^x e^(-t²) dt
"""
def erfc(x):
"""
Complementary error function.
Args:
x: Numeric value
Returns:
erfc(x) = 1 - erf(x)
"""
def zeta(x):
"""
Riemann zeta function.
Args:
x: Numeric value
Returns:
ζ(x) = Σ(n=1 to ∞) 1/n^x
"""
def ai(x):
"""
Airy function Ai(x).
Args:
x: Numeric value
Returns:
Airy function of the first kind
"""
def eint(x):
"""
Exponential integral.
Args:
x: Numeric value
Returns:
Exponential integral Ei(x)
"""
def li2(x):
"""
Dilogarithm function.
Args:
x: Numeric value
Returns:
Li₂(x) = -∫₀^x log(1-t)/t dt
"""def j0(x):
"""Bessel function of the first kind, order 0."""
def j1(x):
"""Bessel function of the first kind, order 1."""
def jn(n, x):
"""
Bessel function of the first kind, order n.
Args:
n: Order (integer)
x: Argument
"""
def y0(x):
"""Bessel function of the second kind, order 0."""
def y1(x):
"""Bessel function of the second kind, order 1."""
def yn(n, x):
"""
Bessel function of the second kind, order n.
Args:
n: Order (integer)
x: Argument
"""def degrees(x):
"""
Convert radians to degrees.
Args:
x: Angle in radians
Returns:
Angle in degrees
"""
def radians(x):
"""
Convert degrees to radians.
Args:
x: Angle in degrees
Returns:
Angle in radians
"""
def hypot(x, y):
"""
Euclidean distance sqrt(x² + y²).
Args:
x, y: Numeric values
Returns:
sqrt(x² + y²)
Note:
Avoids overflow/underflow for large/small values
"""
def remainder(x, y):
"""
IEEE remainder of x / y.
Args:
x, y: Numeric values
Returns:
IEEE remainder
"""
def remquo(x, y):
"""
IEEE remainder and quotient.
Args:
x, y: Numeric values
Returns:
tuple: (remainder, quotient)
"""
def fmod(x, y):
"""
Floating-point remainder of x / y.
Args:
x, y: Numeric values
Returns:
Remainder with same sign as x
"""
def modf(x):
"""
Split into integer and fractional parts.
Args:
x: Numeric value
Returns:
tuple: (fractional_part, integer_part)
"""
def frexp(x):
"""
Extract mantissa and exponent.
Args:
x: Numeric value
Returns:
tuple: (mantissa, exponent) where x = mantissa * 2^exponent
"""
def agm(x, y):
"""
Arithmetic-geometric mean.
Args:
x, y: Positive numeric values
Returns:
Arithmetic-geometric mean of x and y
"""
def fsum(iterable):
"""
Accurate floating-point sum.
Args:
iterable: Sequence of numeric values
Returns:
Accurate sum using current precision
Note:
More accurate than built-in sum() for floating-point
"""def fma(x, y, z):
"""
Fused multiply-add: (x * y) + z.
Args:
x, y, z: Numeric values
Returns:
(x * y) + z computed with single rounding
"""
def fms(x, y, z):
"""
Fused multiply-subtract: (x * y) - z.
Args:
x, y, z: Numeric values
Returns:
(x * y) - z computed with single rounding
"""
def fmma(x, y, z, w):
"""
Fused multiply-multiply-add: (x * y) + (z * w).
Args:
x, y, z, w: Numeric values
Returns:
(x * y) + (z * w) computed with single rounding
"""
def fmms(x, y, z, w):
"""
Fused multiply-multiply-subtract: (x * y) - (z * w).
Args:
x, y, z, w: Numeric values
Returns:
(x * y) - (z * w) computed with single rounding
"""def maxnum(x, y):
"""
Maximum of two numbers (NaN-aware).
Args:
x, y: Numeric values
Returns:
Maximum value, treating NaN specially
"""
def minnum(x, y):
"""
Minimum of two numbers (NaN-aware).
Args:
x, y: Numeric values
Returns:
Minimum value, treating NaN specially
"""def norm(x):
"""
Complex norm (squared magnitude).
Args:
x: Complex number
Returns:
|x|² = real(x)² + imag(x)²
"""
def phase(x):
"""
Complex phase (argument).
Args:
x: Complex number
Returns:
Phase angle in radians
"""
def polar(x):
"""
Convert to polar form.
Args:
x: Complex number
Returns:
tuple: (magnitude, phase)
"""
def proj(x):
"""
Riemann sphere projection.
Args:
x: Complex number
Returns:
Projection onto Riemann sphere
"""
def rect(r, theta):
"""
Convert from polar to rectangular form.
Args:
r: Magnitude
theta: Phase angle in radians
Returns:
Complex number r * e^(i*theta)
"""
def root_of_unity(n, k):
"""
nth root of unity.
Args:
n: Order
k: Index (0 <= k < n)
Returns:
e^(2πik/n)
"""def const_pi(precision=None):
"""
Pi constant.
Args:
precision: Precision in bits (None = use context)
Returns:
π with specified precision
"""
def const_euler(precision=None):
"""
Euler's constant (gamma).
Args:
precision: Precision in bits (None = use context)
Returns:
Euler-Mascheroni constant γ
"""
def const_catalan(precision=None):
"""
Catalan's constant.
Args:
precision: Precision in bits (None = use context)
Returns:
Catalan's constant G
"""
def const_log2(precision=None):
"""
Natural logarithm of 2.
Args:
precision: Precision in bits (None = use context)
Returns:
ln(2) with specified precision
"""import gmpy2
# Set high precision for calculations
with gmpy2.local_context(precision=100):
# High-precision sine and cosine
x = gmpy2.const_pi() / 4 # π/4
sin_val = gmpy2.sin(x)
cos_val = gmpy2.cos(x)
print(f"sin(π/4) = {sin_val}")
print(f"cos(π/4) = {cos_val}")
# Verify sin²(x) + cos²(x) = 1
identity = sin_val**2 + cos_val**2
print(f"sin²(π/4) + cos²(π/4) = {identity}")
# More efficient simultaneous calculation
sin_cos_vals = gmpy2.sin_cos(x)
print(f"sin_cos(π/4) = {sin_cos_vals}")import gmpy2
with gmpy2.local_context(precision=80):
# Natural exponential and logarithm
x = gmpy2.mpfr("2.5")
exp_x = gmpy2.exp(x)
log_exp_x = gmpy2.log(exp_x)
print(f"exp({x}) = {exp_x}")
print(f"log(exp({x})) = {log_exp_x}")
# Small value accuracy
small_x = gmpy2.mpfr("1e-10")
exp_m1_direct = gmpy2.exp(small_x) - 1
exp_m1_accurate = gmpy2.expm1(small_x)
print(f"exp({small_x}) - 1 (direct) = {exp_m1_direct}")
print(f"expm1({small_x}) = {exp_m1_accurate}")import gmpy2
with gmpy2.local_context(precision=60):
# Gamma function
x = gmpy2.mpfr("5.5")
gamma_x = gmpy2.gamma(x)
factorial_equivalent = gmpy2.factorial(x - 1)
print(f"Γ({x}) = {gamma_x}")
print(f"({x-1})! = {factorial_equivalent}")
# Error function
z = gmpy2.mpfr("1.0")
erf_z = gmpy2.erf(z)
erfc_z = gmpy2.erfc(z)
print(f"erf({z}) = {erf_z}")
print(f"erfc({z}) = {erfc_z}")
print(f"erf + erfc = {erf_z + erfc_z}") # Should be 1import gmpy2
# Compare constants at different precisions
precisions = [50, 100, 200]
for prec in precisions:
with gmpy2.local_context(precision=prec):
pi_val = gmpy2.const_pi()
e_val = gmpy2.exp(1)
euler_gamma = gmpy2.const_euler()
print(f"\nPrecision: {prec} bits")
print(f"π = {pi_val}")
print(f"e = {e_val}")
print(f"γ = {euler_gamma}")import gmpy2
with gmpy2.local_context(precision=80):
# Complex number operations
z = gmpy2.mpc("1+2j")
# Complex exponential
exp_z = gmpy2.exp(z)
print(f"exp({z}) = {exp_z}")
# Complex logarithm
log_z = gmpy2.log(z)
print(f"log({z}) = {log_z}")
# Polar form
magnitude, phase_angle = gmpy2.polar(z)
print(f"Polar form: magnitude={magnitude}, phase={phase_angle}")
# Convert back to rectangular
rect_z = gmpy2.rect(magnitude, phase_angle)
print(f"Back to rectangular: {rect_z}")Install with Tessl CLI
npx tessl i tessl/pypi-gmpy2