Mastering Arbitrary Precision in Python with mpmath

Publishers

Sharaf Nada T - Anshika - Radhika Purohit

Published

February 25, 2025

Introduction

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.

Installation & Setup

Windows

pip install mpmath python -c "import mpmath; print(mpmath.__version__)"

Linux

pip install mpmath python3 -c "import mpmath; print(mpmath.__version__)"

macOS

pip install mpmath python3 -c "import mpmath; print(mpmath.__version__)"

Key Features of mpmath

Code Examples

High-Precision Computation of π

from mpmath import mp mp.dps = 50 print(mp.pi)

Computing the Gaussian Integral

from mpmath import mp mp.dps = 50 print(mp.quad(lambda x: mp.exp(-x**2), [-mp.inf, mp.inf]) ** 2)

Numerical Differentiation

from mpmath import diff, sin print(diff(sin, 1))

Solving Ordinary Differential Equations (ODEs)

from mpmath import odefun, exp def f(t, y): return -y + exp(-t) sol = odefun(f, 0, 1) print(sol(1))

Benchmarking mpmath

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)

Mathematical Plots with mpmath

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])

Generated Plots

2D and Complex Function Plot 3D Surface Plot

Conclusion

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.

References & Further Reading

mpmath Official Documentation