2012-11-29 2 views
1

일부 계산에서 나온 수치를보고 있고 그 코드는 원래의 수치를 기반으로 정확한 정밀도를 계산하려고 시도합니다 (계산 전). 다음을 사용하여 반올림을 적용합니다.파이썬 0의 정밀도 낮춤

with localcontext() as ctx: 
    ctx.prec = 5 # simplification for the sake of this example 
    my_figure = +my_figure 

그리고 my_figure가 0이 아닌 한 모든 것이 좋습니다. 이것은 전혀 0에 영향을 미치지 않으므로 이전과 동일한 정밀도로 나타납니다 (이 예제에서는 5가 아님).

my_figure = Decimal('0.0000...') # 0E-30, it comes from some calculations, not assigned like that 
with localcontext() as ctx: 
    ctx.prec = 5 # simplification for the sake of this example 
    my_figure = +my_figure 
    print my_figure # I get 0E-30, no rounding applied, I was expecting 0.0000 

이 그것뿐만 아니라 영에 영향을 미치는 방식 일의 적절한 방법이 있나요?

+3

'my_figure'는'decimal()'이 아닌'float()'입니다. 'localcontext()'는 float에는 적용되지 않고'decimal.Decimal()'인스턴스에만 적용됩니다. –

+1

'my_figure = + my_figure'는 어떻게해야합니까? (그것은'abs (my_figure)'또는'my_figure + = my_figure' 일까?)? –

+0

@MartijnPieters 10 진수입니다. 미안 해요. – nirvanka

답변

0

Decimal.normalize은 원하는 것을 수행합니까? 정밀도를 5dp로 유지하지는 않지만 최소한 0E-30을 현명한 것으로 축소합니다.