mpmath Python
Produce arbitrary-precision numerical code with explicit input precision,
working precision, conditioning, convergence evidence, and output accuracy.
Core model
| Object/context |
Meaning |
Rule |
mp.mpf |
Arbitrary-precision real floating value. |
Construct from strings/integers when decimal input must be preserved. |
mp.mpc |
Arbitrary-precision complex value. |
Define branch and complex-domain expectations. |
mp context |
Global/default precision and algorithms. |
Avoid leaking precision changes across callers. |
workdps/workprec |
Scoped absolute decimal/binary working precision. |
Prefer when the function owns a precision target. |
extradps/extraprec |
Scoped precision added to the current context. |
Prefer when guard precision is relative to the caller. |
iv context |
Interval arithmetic values. |
Use only with interval-specific containment semantics. |
| matrix |
Dense arbitrary-precision matrix. |
Suitable for modest sizes; define conditioning and shape. |
Arbitrary precision does not repair an inexact Python float. mp.mpf(0.1)
captures the already-rounded binary value; mp.mpf("0.1") represents the
decimal input at current precision. Precision controls arithmetic performed
after construction, not hidden source accuracy. Read numbers and precision.
Ordered workflow
- Define the mathematical quantity, real/complex domain, target error (absolute,
relative, or digits), and credible input accuracy.
- Construct constants without premature binary-float rounding.
- Estimate conditioning/singularities and choose a stable formulation and
algorithm before increasing precision.
- Compute inside scoped guard digits; never change global
mp.dps without
restoring it.
- Repeat at higher working precision or with another method and compare a
residual, enclosure, or known identity.
- Round/serialize only at the output boundary and report achieved evidence,
not merely configured digits.
- Test near singularities, cancellation, complex branches, poor initial guesses,
non-convergence, and inputs whose original accuracy is lower than
mp.dps.
Intent map
- Use direct special functions before reimplementing series or converting
through machine floats.
- Use
quad/specialized quadrature after splitting discontinuities or difficult
intervals and defining endpoint behavior.
- Use
findroot with an initial guess/interval suited to the solver, then check
the residual independently. verify=False removes one check; it does not make
a root valid.
- Use
diff, numerical sums/products, ODE, transform, or matrix routines only
after checking their documented convergence and domain contract.
- Use
workdps(total_digits) for a local absolute precision target; use
extraprec/extradps when guard precision is relative to the caller.
- Use interval arithmetic when a guaranteed enclosure is required and the
interval algorithm actually provides it. Do not assume
iv.findroot encloses
a root; the official documentation explicitly warns otherwise.
Read algorithms and validation.
Canonical anchor
from mpmath import mp
def _exp_ratio_at(x_text: str, work_digits: int) -> mp.mpf:
with mp.workdps(work_digits):
# Construct inside the context: mpf rounds input at current precision.
x = mp.mpf(x_text)
return mp.expm1(x) / x if x else mp.one
def stable_cancellation(x_text: str, digits: int = 50) -> mp.mpf:
if digits < 2:
raise ValueError("digits must be at least 2")
lower = _exp_ratio_at(x_text, digits + 10)
higher = _exp_ratio_at(x_text, digits + 20)
with mp.workdps(digits):
lower_rounded = +lower
higher_rounded = +higher
if lower_rounded != higher_rounded:
raise ArithmeticError("result did not stabilize at requested precision")
return higher_rounded
The stable formulation matters more than simply raising mp.dps. Constructing
the input inside each working context prevents caller precision from truncating
the decimal first. Unary plus inside workdps(digits) explicitly rounds the
returned value to the requested precision; merely leaving a context does not.
High-risk rules
- Never seed a high-precision computation with an accidental Python float when
the original decimal or exact ratio is available.
- Do not promise
dps correct digits. Guard digits and precision-doubling tests
provide evidence; ill-conditioning can consume them.
- Do not compare high-precision outputs to machine-float expected values as the
oracle. Use exact identities, strings, independent methods, or higher precision.
- Root-finding success requires a small residual and the intended root/domain.
Multiple roots and steep/flat functions can defeat naive convergence checks.
- Quadrature requires singularity, oscillation, infinite interval, and branch
analysis. Split intervals or select specialized methods under a documented rule.
- Global context mutations create order-dependent tests and concurrency hazards.
Scope them with context managers or clone a context where isolation is needed.
- Mixing mpmath and NumPy often creates
object arrays or downcasts to float.
Make conversion, vectorization, and precision loss explicit.
- Formatting many digits is not evidence they are correct.
Version grounding and completion
Official current documentation identifies mpmath 1.3.0. It is not installed in
this foundry. Inspect version, context behavior, and exact callable signatures
before relying on them. Read verification.
Completion requires exact input construction, a scoped precision policy, a
stable algorithm, residual/enclosure or precision-doubling evidence, domain and
failure handling, and serialization that does not silently reduce accuracy.
References
- Numbers and precision
- Algorithms and validation
- Verification and grounding
1---2name: mpmath-python3description: Use for writing, reviewing, debugging, testing, or validating Python mpmath arbitrary-precision numerical code. Trigger on mpf, mpc, mp.dps, workdps, interval arithmetic, high-precision quadrature, root finding, special functions, matrices, inverse transforms, or precision/convergence failures. Do not use for ordinary NumPy vectorization, SymPy symbolic manipulation, decimal currency arithmetic, or machine-float code with no precision requirement.4argument-hint: "[mpmath computation, precision target, code, or failure]"5metadata:6 source: https://skillmd.com/skills/schattenspiegel/mpmath-python7---89# mpmath Python1011Produce arbitrary-precision numerical code with explicit input precision,12working precision, conditioning, convergence evidence, and output accuracy.1314## Core model1516| Object/context | Meaning | Rule |17|---|---|---|18| `mp.mpf` | Arbitrary-precision real floating value. | Construct from strings/integers when decimal input must be preserved. |19| `mp.mpc` | Arbitrary-precision complex value. | Define branch and complex-domain expectations. |20| `mp` context | Global/default precision and algorithms. | Avoid leaking precision changes across callers. |21| `workdps`/`workprec` | Scoped absolute decimal/binary working precision. | Prefer when the function owns a precision target. |22| `extradps`/`extraprec` | Scoped precision added to the current context. | Prefer when guard precision is relative to the caller. |23| `iv` context | Interval arithmetic values. | Use only with interval-specific containment semantics. |24| matrix | Dense arbitrary-precision matrix. | Suitable for modest sizes; define conditioning and shape. |2526Arbitrary precision does not repair an inexact Python float. `mp.mpf(0.1)`27captures the already-rounded binary value; `mp.mpf("0.1")` represents the28decimal input at current precision. Precision controls arithmetic performed29after construction, not hidden source accuracy. Read [numbers and precision](references/precision.md).3031## Ordered workflow32331. Define the mathematical quantity, real/complex domain, target error (absolute,34 relative, or digits), and credible input accuracy.352. Construct constants without premature binary-float rounding.363. Estimate conditioning/singularities and choose a stable formulation and37 algorithm before increasing precision.384. Compute inside scoped guard digits; never change global `mp.dps` without39 restoring it.405. Repeat at higher working precision or with another method and compare a41 residual, enclosure, or known identity.426. Round/serialize only at the output boundary and report achieved evidence,43 not merely configured digits.447. Test near singularities, cancellation, complex branches, poor initial guesses,45 non-convergence, and inputs whose original accuracy is lower than `mp.dps`.4647## Intent map4849- Use direct special functions before reimplementing series or converting50 through machine floats.51- Use `quad`/specialized quadrature after splitting discontinuities or difficult52 intervals and defining endpoint behavior.53- Use `findroot` with an initial guess/interval suited to the solver, then check54 the residual independently. `verify=False` removes one check; it does not make55 a root valid.56- Use `diff`, numerical sums/products, ODE, transform, or matrix routines only57 after checking their documented convergence and domain contract.58- Use `workdps(total_digits)` for a local absolute precision target; use59 `extraprec`/`extradps` when guard precision is relative to the caller.60- Use interval arithmetic when a guaranteed enclosure is required and the61 interval algorithm actually provides it. Do not assume `iv.findroot` encloses62 a root; the official documentation explicitly warns otherwise.6364Read [algorithms and validation](references/operations.md).6566## Canonical anchor6768```python69from mpmath import mp707172def _exp_ratio_at(x_text: str, work_digits: int) -> mp.mpf:73 with mp.workdps(work_digits):74 # Construct inside the context: mpf rounds input at current precision.75 x = mp.mpf(x_text)76 return mp.expm1(x) / x if x else mp.one777879def stable_cancellation(x_text: str, digits: int = 50) -> mp.mpf:80 if digits < 2:81 raise ValueError("digits must be at least 2")82 lower = _exp_ratio_at(x_text, digits + 10)83 higher = _exp_ratio_at(x_text, digits + 20)84 with mp.workdps(digits):85 lower_rounded = +lower86 higher_rounded = +higher87 if lower_rounded != higher_rounded:88 raise ArithmeticError("result did not stabilize at requested precision")89 return higher_rounded90```9192The stable formulation matters more than simply raising `mp.dps`. Constructing93the input inside each working context prevents caller precision from truncating94the decimal first. Unary plus inside `workdps(digits)` explicitly rounds the95returned value to the requested precision; merely leaving a context does not.9697## High-risk rules9899- Never seed a high-precision computation with an accidental Python float when100 the original decimal or exact ratio is available.101- Do not promise `dps` correct digits. Guard digits and precision-doubling tests102 provide evidence; ill-conditioning can consume them.103- Do not compare high-precision outputs to machine-float expected values as the104 oracle. Use exact identities, strings, independent methods, or higher precision.105- Root-finding success requires a small residual and the intended root/domain.106 Multiple roots and steep/flat functions can defeat naive convergence checks.107- Quadrature requires singularity, oscillation, infinite interval, and branch108 analysis. Split intervals or select specialized methods under a documented rule.109- Global context mutations create order-dependent tests and concurrency hazards.110 Scope them with context managers or clone a context where isolation is needed.111- Mixing mpmath and NumPy often creates `object` arrays or downcasts to float.112 Make conversion, vectorization, and precision loss explicit.113- Formatting many digits is not evidence they are correct.114115## Version grounding and completion116117Official current documentation identifies mpmath 1.3.0. It is not installed in118this foundry. Inspect version, context behavior, and exact callable signatures119before relying on them. Read [verification](references/verification.md).120121Completion requires exact input construction, a scoped precision policy, a122stable algorithm, residual/enclosure or precision-doubling evidence, domain and123failure handling, and serialization that does not silently reduce accuracy.124125## References126127- [Numbers and precision](references/precision.md)128- [Algorithms and validation](references/operations.md)129- [Verification and grounding](references/verification.md)