Sharaf Nada T - Anshika - Radhika Purohit
February 25, 2025
Precision matters in scientific computing. Whether you're tackling complex physics simulations, financial modeling, or AI computations, tiny floating-point errors can snowball into major inaccuracies. Python’s built-in math module is great for general-purpose calculations, but when you need extreme precision, it falls short.
Enter mpmath—a powerful, arbitrary-precision arithmetic library for Python. Developed by Fredrik Johansson since 2007, mpmath allows you to perform calculations with thousands of decimal places, making it indispensable for researchers, engineers, and mathematicians alike.
pip install mpmath
python -c "import mpmath; print(mpmath.__version__)"
pip install mpmath
python3 -c "import mpmath; print(mpmath.__version__)"
pip install mpmath
python3 -c "import mpmath; print(mpmath.__version__)"
from mpmath import mp
mp.dps = 50
print(mp.pi)
from mpmath import mp
mp.dps = 50
print(mp.quad(lambda x: mp.exp(-x**2), [-mp.inf, mp.inf]) ** 2)
from mpmath import diff, sin
print(diff(sin, 1))
from mpmath import odefun, exp
def f(t, y):
return -y + exp(-t)
sol = odefun(f, 0, 1)
print(sol(1))
from decimal import Decimal, getcontext
from mpmath import mp, sqrt
import time
getcontext().prec = 50
start = time.time()
Decimal(2).sqrt()
end = time.time()
print("Decimal sqrt time:", end - start)
mp.dps = 50
start = time.time()
sqrt(2)
end = time.time()
print("mpmath sqrt time:", end - start)
from mpmath import *
# 2D plot example
plot(lambda x: exp(x)*li(x), [1, 4])
# Complex function plot example
cplot(lambda z: z, [-2, 2], [-10, 10])
# 3D surface plot example
def f(x, y):
return sin(x+y)*cos(y)
splot(f, [-pi,pi], [-pi,pi])
mpmath is a robust and versatile library for anyone dealing with high-precision numerical computations. Whether you're a researcher, engineer, or financial analyst, mpmath ensures that your calculations are as accurate as possible.