Decimal 模块不适用于 Numpy 或 Scipy

Decimal module is not working with Numpy or Scipy

我想使用 Decimal 模块。

getcontext().prec = 3
d1 = Decimal("0.1")
a = float(0.20052)
b = str(a)
d2 = Decimal(b)
q = d1+d2
print(q) ###0.301

getcontext().prec = 1
d1 = Decimal("0.1")
a = float(0.20052)
b = str(a)
d2 = Decimal(b)
q = d1+d2
print(q)##0.3

正在工作。

但是,下面的代码不起作用。我想要“0.0.”

np.random.seed(12345678)  #fix random seed to get the same result
n1 = 200  # size of first sample
n2 = 300  # size of second sample
rvs1 = stats.norm.rvs(size=n1, loc=0., scale=1)
rvs2 = stats.norm.rvs(size=n2, loc=0.5, scale=1.5)

print(stats.mannwhitneyu(rvs1, rvs2))###MannwhitneyuResult(statistic=25639.0, pvalue=0.0029339910470636116)
p_value = stats.mannwhitneyu(rvs1, rvs2).pvalue
print(p_value)###0.0029339910470636116
p_str = str(p_value)
getcontext().prec = 1
p_n = Decimal(p_str)
print(p_n)###0.0029339910470636116

我看到了,也用了item法,但是结果没变。我想要“0.0029.”

getcontext().prec = 4
p2 = Decimal(p_value.item())
print(p2)####0.0029339910470636116311682339841127031832002103328704833984375

MacOS 10.14.5; python3.7.2; jupyter 笔记本 4.4.0;麻木的 1.17.2; scipy1.2.1

另外,我想要“0.0029”但是结果如下图

getcontext().prec = 4
p_n = Decimal(p_str)
print(p_n)##0.0029339910470636116
p_n = Decimal(p_str) + 0
print(p_n)##0.002934
p_n = Context(prec=4).create_decimal(p_str)+0
print(p_n)##0.002934

... the result has not changed.

这里有概念上的差距。

正在更改当前 contextprec 改变方式,例如__add__( ... ) 行为。 它不会改变构造函数的行为方式——如果你提供 高精度输入 ctor 仍将提供高精度输出。 考虑这个演示:

>>> getcontext().prec = 1
>>> 
>>> Decimal('.12345') 
Decimal('0.12345')
>>> 
>>> Decimal('.12345') + 0
Decimal('0.1')

当然,prec 属性对 使用 IEEE-754 FP 操作的无关数学包,例如 numpy。 如果 p_value 有很多位数的精度, 那么 Decimal(p_value) 也就不足为奇了 将报告许多精度数字。 也许您想添加 0