不,这不是重复的,上面的链接正是我所指的不是正确答案。该链接和我在此处的帖子专门询问有关生成十进制列表的问题。但是“答案”会产生一个 float 列表。
正确答案是在 np.arange 中使用 Decimal 参数,如下所示 `x_values = np.arange(十进制(-2.0), 十进制(2.0), 十进制(0.1)) 谢谢https://stackoverflow.com/users/2084384/boargules
我相信这可能在别处得到解答,但我发现的答案似乎是错误的。我想要一个从 -2 到 2 的小数列表(精度 = 1 个小数位)。 -2, -1.9, -1.8 ... 1.8, 1.9, 2.0
当我这样做时:
import numpy as np
x_values = np.arange(-2,2,0.1)
x_values
我得到:
array([ -2.00000000e+00, -1.90000000e+00, -1.80000000e+00, ...
我试过:
from decimal import getcontext, Decimal
getcontext().prec = 2
x_values = [x for x in np.around(np.arange(-2, 2, .1), 2)]
x_values2 = [Decimal(x) for x in x_values]
x_values2
我得到:
[Decimal('-2'),
Decimal('-1.899999999999999911182158029987476766109466552734375'),
Decimal('-1.8000000000000000444089209850062616169452667236328125'), ...
我在 jupyter notebook 中运行 3.6.3。
更新:我将范围从 2 更改为 2.0。这改进了结果,但我仍然遇到舍入错误:
import numpy as np
x_values = np.arange(-2.0, 2.0, 0.1)
x_values
产生:
-2.00000000e+00, -1.90000000e+00, -1.80000000e+00, ...
1.00000000e-01, 1.77635684e-15, 1.00000000e-01, ...
1.80000000e+00, 1.90000000e+00
注意 1.77635684e-15 可能是一个非常小的数字,但它不是零。零测试将失败。因此输出是错误的。
我对重复断言的回应。正如您从我的结果中看到的那样,答案在 How to use a decimal range() step value?不会产生我在不同范围内看到的相同结果。具体来说, float 仍在返回且未四舍五入,并且 1.77635684e-15 不等于零。
请您参考如下方法:
围绕简单解决方案的讨论和重复舞蹈:
In [177]: np.arange(Decimal('-2.0'), Decimal('2.0'), Decimal('0.1'))
Out[177]:
array([Decimal('-2.0'), Decimal('-1.9'), Decimal('-1.8'), Decimal('-1.7'),
Decimal('-1.6'), Decimal('-1.5'), Decimal('-1.4'), Decimal('-1.3'),
Decimal('-1.2'), Decimal('-1.1'), Decimal('-1.0'), Decimal('-0.9'),
Decimal('-0.8'), Decimal('-0.7'), Decimal('-0.6'), Decimal('-0.5'),
Decimal('-0.4'), Decimal('-0.3'), Decimal('-0.2'), Decimal('-0.1'),
Decimal('0.0'), Decimal('0.1'), Decimal('0.2'), Decimal('0.3'),
Decimal('0.4'), Decimal('0.5'), Decimal('0.6'), Decimal('0.7'),
Decimal('0.8'), Decimal('0.9'), Decimal('1.0'), Decimal('1.1'),
Decimal('1.2'), Decimal('1.3'), Decimal('1.4'), Decimal('1.5'),
Decimal('1.6'), Decimal('1.7'), Decimal('1.8'), Decimal('1.9')],
dtype=object)
将浮点值赋予 Decimal 效果不佳:
In [180]: np.arange(Decimal(-2.0), Decimal(2.0), Decimal(0.1))
Out[180]:
array([Decimal('-2'), Decimal('-1.899999999999999994448884877'),
Decimal('-1.799999999999999988897769754'),
Decimal('-1.699999999999999983346654631'),
因为 Decimal(0.1) 只是巩固了 0.1 的浮点不精度:
In [178]: Decimal(0.1)
Out[178]: Decimal('0.1000000000000000055511151231257827021181583404541015625')
