Python 3中如何生成Decimal类型列表?正确实现方案说明
It’s easy to run into the mistake of generating a float list when you actually need a Decimal type list, and many existing solutions overlook this key detail. The critical fix here is to pass Decimal instances directly to np.arange instead of using float values.
The Correct Implementation
By providing Decimal-type arguments for the start, stop, and step parameters in np.arange, NumPy will create an array where every element is a Decimal object—exactly what you need to avoid floating-point precision issues.
Here’s the working code example:
from decimal import Decimal import numpy as np # Generate a list of Decimal values using np.arange x_values = np.arange(Decimal(-2.0), Decimal(2.0), Decimal(0.1))
This approach ensures that all values in x_values are of type Decimal, not float, which aligns perfectly with the requirement to generate a Decimal type list.
内容的提问来源于stack exchange,提问作者SteveO250k

