Python library for arbitrary-precision floating-point arithmetic
—
Basic number types, arithmetic operations, precision control, and utility functions that form the foundation for all mathematical computations in mpmath.
Create multiprecision floating-point and complex numbers from various input types.
class mpf:
"""
Multiprecision floating-point number.
Args:
x: Input value (int, float, str, mpf, or fraction)
"""
def __init__(self, x): ...
class mpc:
"""
Multiprecision complex number.
Args:
real: Real part (number or string)
imag: Imaginary part (number or string), default 0
"""
def __init__(self, real, imag=0): ...
def mpmathify(x):
"""
Convert input to appropriate mpmath number type.
Args:
x: Value to convert
Returns:
mpf, mpc, or original type as appropriate
"""
# Alias for mpmathify
convert = mpmathifyControl precision settings globally or within specific contexts.
def extraprec(n):
"""
Context manager to temporarily increase precision by n bits.
Args:
n (int): Additional precision in bits
"""
def extradps(n):
"""
Context manager to temporarily increase precision by n decimal places.
Args:
n (int): Additional precision in decimal places
"""
def workprec(n):
"""
Context manager to set working precision to n bits.
Args:
n (int): Precision in bits
"""
def workdps(n):
"""
Context manager to set working precision to n decimal places.
Args:
n (int): Precision in decimal places
"""
def autoprec(f):
"""
Decorator for automatic precision adjustment.
Args:
f: Function to decorate
"""
def maxcalls(n):
"""
Context manager to limit function evaluation calls.
Args:
n (int): Maximum number of calls
"""
def memoize(f):
"""
Decorator to add memoization to a function.
Args:
f: Function to memoize
"""Low-level arithmetic operations for maximum control and efficiency.
def fadd(x, y):
"""
Add two numbers.
Args:
x, y: Numbers to add
Returns:
Sum of x and y
"""
def fsub(x, y):
"""
Subtract y from x.
Args:
x, y: Numbers for subtraction
Returns:
Difference x - y
"""
def fmul(x, y):
"""
Multiply two numbers.
Args:
x, y: Numbers to multiply
Returns:
Product of x and y
"""
def fdiv(x, y):
"""
Divide x by y.
Args:
x, y: Numbers for division
Returns:
Quotient x / y
"""
def fneg(x):
"""
Negate a number.
Args:
x: Number to negate
Returns:
-x
"""
def fprod(sequence):
"""
Compute product of sequence of numbers.
Args:
sequence: Iterable of numbers
Returns:
Product of all numbers in sequence
"""
def fsum(sequence):
"""
Accurately sum a sequence of numbers.
Args:
sequence: Iterable of numbers
Returns:
Sum of all numbers in sequence
"""
def fdot(x, y):
"""
Compute dot product of two sequences.
Args:
x, y: Sequences of numbers
Returns:
Dot product sum(x[i] * y[i])
"""Functions to test properties of numbers and extract information.
def isinf(x):
"""
Test if x is infinite.
Args:
x: Number to test
Returns:
bool: True if x is infinite
"""
def isnan(x):
"""
Test if x is NaN (not a number).
Args:
x: Number to test
Returns:
bool: True if x is NaN
"""
def isnormal(x):
"""
Test if x is a normal number.
Args:
x: Number to test
Returns:
bool: True if x is normal
"""
def isint(x):
"""
Test if x is an integer.
Args:
x: Number to test
Returns:
bool: True if x is an integer
"""
def isfinite(x):
"""
Test if x is finite.
Args:
x: Number to test
Returns:
bool: True if x is finite
"""
def almosteq(x, y, rel_eps=None, abs_eps=None):
"""
Test if two numbers are approximately equal.
Args:
x, y: Numbers to compare
rel_eps: Relative tolerance
abs_eps: Absolute tolerance
Returns:
bool: True if numbers are approximately equal
"""
def sign(x):
"""
Return the sign of x.
Args:
x: Number
Returns:
-1, 0, or 1 depending on sign of x
"""
def mag(x):
"""
Return the magnitude (order of magnitude) of x.
Args:
x: Number
Returns:
int: Magnitude of x
"""Operations specific to complex numbers.
def re(z):
"""
Return real part of complex number.
Args:
z: Complex number
Returns:
Real part of z
"""
def im(z):
"""
Return imaginary part of complex number.
Args:
z: Complex number
Returns:
Imaginary part of z
"""
def conj(z):
"""
Return complex conjugate.
Args:
z: Complex number
Returns:
Complex conjugate of z
"""
def arg(z):
"""
Return argument (phase) of complex number.
Args:
z: Complex number
Returns:
Argument of z in radians
"""
def phase(z):
"""
Return phase of complex number (alias for arg).
Args:
z: Complex number
Returns:
Phase of z in radians
"""
def polar(z):
"""
Convert complex number to polar form.
Args:
z: Complex number
Returns:
tuple: (magnitude, phase)
"""
def rect(r, phi):
"""
Convert from polar to rectangular form.
Args:
r: Magnitude
phi: Phase in radians
Returns:
Complex number in rectangular form
"""Functions for controlling number display and string conversion.
def nstr(x, n=None, **kwargs):
"""
Convert number to string with specified precision.
Args:
x: Number to convert
n: Number of digits to display
**kwargs: Additional formatting options
Returns:
str: String representation of number
"""
def nprint(x, n=None, **kwargs):
"""
Print number with specified precision.
Args:
x: Number to print
n: Number of digits to display
**kwargs: Additional formatting options
"""
def chop(x, tol=None):
"""
Round small numbers to zero.
Args:
x: Number to chop
tol: Tolerance for chopping
Returns:
Number with small values rounded to zero
"""Miscellaneous utility functions for working with numbers.
def fraction(x, tol=None):
"""
Convert number to rational fraction representation.
Args:
x: Number to convert
tol: Tolerance for conversion
Returns:
Rational representation as (numerator, denominator)
"""
def rand():
"""
Generate random number between 0 and 1.
Returns:
Random mpf between 0 and 1
"""
def linspace(a, b, n):
"""
Generate linearly spaced array.
Args:
a: Start value
b: End value
n: Number of points
Returns:
list: Array of n evenly spaced values
"""
def arange(start, stop=None, step=1):
"""
Generate arithmetic progression.
Args:
start: Start value (or stop if stop is None)
stop: End value (optional)
step: Step size
Returns:
list: Arithmetic progression
"""
def absmin(*args):
"""
Return argument with minimum absolute value.
Args:
*args: Numbers to compare
Returns:
Number with minimum absolute value
"""
def absmax(*args):
"""
Return argument with maximum absolute value.
Args:
*args: Numbers to compare
Returns:
Number with maximum absolute value
"""
def nint_distance(x):
"""
Return distance to nearest integer.
Args:
x: Number
Returns:
Distance to nearest integer
"""
def make_mpf(s):
"""
Create mpf number from internal representation.
Args:
s: Internal representation
Returns:
mpf number
"""
def make_mpc(real, imag=None):
"""
Create mpc number from components.
Args:
real: Real part
imag: Imaginary part (optional)
Returns:
mpc number
"""
# Package version
__version__ # Version string of mpmath packageArithmetic contexts that control precision and behavior of mathematical operations.
# Main contexts
mp # MPContext - multiprecision arithmetic (default)
fp # FPContext - fast double-precision arithmetic
iv # MPIntervalContext - interval arithmetic
class MPContext:
"""
Multiprecision arithmetic context with configurable precision.
Attributes:
dps: Decimal precision (number of decimal places)
prec: Binary precision (number of bits)
pretty: Pretty printing mode
"""
def workprec(self, n):
"""Context manager for temporary precision change."""
def workdps(self, n):
"""Context manager for temporary decimal precision change."""
def extraprec(self, n):
"""Context manager for additional precision."""
class FPContext:
"""
Fast double-precision floating-point context.
Uses hardware floating-point for maximum speed.
"""
class MPIntervalContext:
"""
Interval arithmetic context for rigorous computation.
All operations return intervals containing exact results.
"""
# Interval number type
class mpi:
"""
Multiprecision interval [a, b].
Args:
a: Lower bound
b: Upper bound (optional, defaults to a)
"""
def __init__(self, a, b=None): ...Basic mathematical constants and special values.
# Special values
inf # Positive infinity
ninf # Negative infinity
nan # Not a number
j # Imaginary unit
eps # Machine epsilonimport mpmath
from mpmath import mp, mpf, mpc
# Set precision
mp.dps = 30 # 30 decimal places
# Create high-precision numbers
x = mpf('1.23456789012345678901234567890')
y = mpf(2) # Can use regular numbers too
# Basic arithmetic
print(f"Sum: {x + y}")
print(f"Product: {x * y}")
# Complex numbers
z1 = mpc(1, 2) # 1 + 2j
z2 = mpc('3.14159', '2.71828')
print(f"Complex sum: {z1 + z2}")
# Precision control
with mp.workdps(50): # Temporarily use 50 decimal places
high_precision_result = mpf(1) / mpf(3)
print(f"1/3 with 50 digits: {high_precision_result}")
# Testing number properties
print(f"Is {x} finite? {mp.isfinite(x)}")
print(f"Is infinity finite? {mp.isfinite(mp.inf)}")
# Complex number operations
z = mpc(3, 4)
print(f"Magnitude: {abs(z)}")
print(f"Phase: {mp.arg(z)}")
print(f"Real part: {mp.re(z)}")
print(f"Imaginary part: {mp.im(z)}")