简体   繁体   中英

How to disable rounding in Decimal python?

When calculating, I get the wrong last digit of the number. At first, I just calculated with an accuracy of one digit more than I needed, and then I just removed the last rounded digit with a slice. But then I noticed that sometimes Decimal rounds more than one digit. Is it possible to calculate without rounding?

For example

from decimal import Decimal as dec, Context, setcontext, ROUND_DOWN
from math import log

def sqr(x):
    return x*x

def pi(n):
    getcontext().prec=n+1
    a=p=1
    b=dec(1)/dec(2).sqrt()
    t=dec(1)/dec(4)
    for _ in range(int(log(n,2))):
        an=(a+b)/2
        b=(a*b).sqrt()
        t-=p*sqr(a-an)
        p*=2
        a=an
    return sqr(a+b)/(4*t)

If I try pi (12) I get "3.141592653591" (the last 2 digits are wrong), but if I try pi(13), they both change to the correct ones - "3.1415926535899".

It's called Roundoff Error and is unavoidable when working with Floating-Point Arithmetic . You can write the following code in your Python REPL and should get, interestingly, False .

0.2 + 0.1 == 0.3 # False

It's because the last bits of float numbers are, actually, garbage. One way you can work around this is by using more terms in your series and, then, rounding the result to the wanted precision.

If you want to understand this deeper, you can read these two links I've attached and, maybe, some Numerical Computing textbook.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM