mpmath is a Python library for arbitrary-precision floating-point arithmetic, currently at version 1.4.1, with a release cadence of approximately every 1-2 years.
pip install mpmathVerified import paths — ran on the pinned version, not inferred.
This example computes 50 digits of pi by numerically evaluating the Gaussian integral using mpmath.
Use explicit imports like 'from mpmath import mp, mpf' or access functions via 'mpmath.'
Use explicit imports or access functions via 'mpmath.'
Install the mpmath library using pip or conda: `pip install mpmath` or `conda install mpmath`
Pin the mpmath version to a compatible older release, such as 1.3.0, or update the dependent library if a version compatible with newer mpmath releases is available. `pip install mpmath==1.3.0`
Explicitly convert the input to a standard Python float or a string before passing it to `mpmath.mpf` or an `mpmath` function. For NumPy types, cast to `float` first. ```python from mpmath import mpf import numpy as np # Original problematic code (example with numpy.int64) # x_np_int = np.int64(1) # m_val = mpf(x_np_int) # This would raise the TypeError # Corrected code x_np_int = np.int64(1) m_val = mpf(float(x_np_int)) # Convert to Python float first print(m_val) # Example with a numpy array (common when plotting) # import mpmath # arr = np.array([1.0, 2.0, 3.0]) # mpmath.cos(arr) # This would raise the TypeError # Corrected code for array element-wise operations import mpmath arr = np.array([1.0, 2.0, 3.0]) m_arr = [mpmath.cos(mpmath.mpf(x)) for x in arr] print(m_arr) ```
Convert the `mpmath.mpf` object (or the float) to a standard Python integer using `int()` before passing it to functions or operations that expect an integer.
```python
from mpmath import mp
# Original problematic code
# mp.dps = 15
# num_iterations_float = mp.sqrt(25.0)
# for i in range(num_iterations_float): # This would raise the TypeError
# print(i)
# Corrected code
mp.dps = 15
num_iterations_mpf = mp.sqrt(25.0) # This is an mpf object equivalent to 5.0
num_iterations_int = int(num_iterations_mpf) # Convert mpf to Python int
for i in range(num_iterations_int):
print(i)
# Example with numpy.linspace num argument
import numpy as np
# interval_len = mp.pi / 2
# x_values = np.linspace(0, float(mp.pi), num=interval_len) # This would raise TypeError if interval_len is mpf
# Corrected code
interval_len_mpf = mp.pi / 2 # This is an mpf object
interval_len_int = int(interval_len_mpf.real) # Convert mpf to Python int (using .real for complex mpf)
x_values = np.linspace(0, float(mp.pi), num=interval_len_int)
print(x_values)
```