如何创建具有给定数量有效数字的decimal.Decimal对象? [英] How to create a decimal.Decimal object with a given number of significant figures?
问题描述
我发现生成 decimal.Decimal
数字的最佳方法,该数字具有特定的 重要数字 是用于初始化以下变量 kluge
的数字:
The best way I've found to produce a decimal.Decimal
number with a specific number of significant figures is the one used to initialize the variable kluge
below:
import decimal
THIS_IS_JUST_AN_EXAMPLE = 0.00001/3.0
with decimal.localcontext() as c:
c.prec = 5
kluge = decimal.Decimal(THIS_IS_JUST_AN_EXAMPLE) + decimal.Decimal(0)
naive = decimal.Decimal(THIS_IS_JUST_AN_EXAMPLE)
print repr(kluge)
print repr(naive)
# Decimal('0.0000033333')
# Decimal('0.00000333333333333333374718233758915442166426146286539733409881591796875')
输出的第一行显示所需的 decimal.Decimal
数字,其中有5位有效数字。输出的第二行显示如果不添加
The first line of output shows the desired decimal.Decimal
number, with 5 significant figures. The second line in the output shows what happens if one does not add the
+ decimal.Decimal(0)
到初始化的RHS;
即使没有 +十进制。Decimal(0)
创建十进制
具有所需的有效数字?
What's the correct approach to creating a Decimal
with a desired number of significant figures?
此问题不是将Python小数对象的格式设置为指定的精度。看看下面的输出。
This question is not a duplicate of Format Python Decimal object to a specified precision. Look at the output below.
import math
import decimal
base = math.pi
with decimal.localcontext() as c:
c.prec = 13
for exponent in [6, 4, 2, 0, -2, -4, -6]:
scale = 10**exponent
kluge = decimal.Decimal(base * scale) + decimal.Decimal(0)
print repr(kluge)
# Decimal('3141592.653590')
# Decimal('31415.92653590')
# Decimal('314.1592653590')
# Decimal('3.141592653590')
# Decimal('0.03141592653590')
# Decimal('0.0003141592653590')
# Decimal('0.000003141592653590')
使用将Python小数对象格式化为指定精度的答案中给出的方法,无法获得上述输出,这仅仅是因为此问题与格式化输出无关。
The items shown in the output above cannot be obtained using the method given in the answer to Format Python Decimal object to a specified precision, simply because this question has nothing to do with formatting output.
此问题与如何使用特定于的m odule ( decimal
)创建该模块定义的类的某些对象。更具体地说,它是在寻找一种使用 decimal
模块来获得所示结果的方法,而不必求助于添加 decimal.Decimal(0 )
。
This question is about how to use a specific module (decimal
) to create certain objects of a class defined by that module. More specifically, it is about looking for a way to use the decimal
module to achieve the result shown without having to resort to adding decimal.Decimal(0)
.
推荐答案
您似乎正在寻找 Context.create_decimal
:
You seem to be looking for Context.create_decimal
:
使用 self 作为上下文,从 num 创建一个新的Decimal实例。
与Decimal
构造函数不同,上下文精度,舍入
方法,标志和陷阱将应用于转换。
Creates a new Decimal instance from num but using self as context. Unlike the
Decimal
constructor, the context precision, rounding method, flags, and traps are applied to the conversion.
>>> decimal.Context(prec=5).create_decimal(0.00001/3.0)
Decimal('0.0000033333')
这篇关于如何创建具有给定数量有效数字的decimal.Decimal对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!