precision in python upto 50 decimal places

3.9k views Asked by At

I am trying to code to find out the radius of the inner soddy circles, the code is running fine but i am not getting the required precision, i want the answer to be truncated to 50 digits Please suggest how can i get more precise calculations How should i obtain the precision of 50 digits

import math
t=input()
while t>0:
    t-=1
    r1,r2,r3=map(int,raw_input().split())
    k1=1.0/r1
    k2=1.0/r2
    k3=1.0/r3
    k4=k1+k2+k3+2*math.sqrt(k1*k2+k2*k3+k3*k1)
    r4=1.0/k4
    print r4
2

There are 2 answers

10
aIKid On

Use the decimal module. Store all the variables you're using as decimal.Decimal objects.

Updated code:

from decimal import *
import math
context = Context(prec=1000)
setcontext(context)
t=input()
while t>0:
    t-=1
    r1,r2,r3=map(Decimal,raw_input().split())
    k1=Decimal(1.0)/Decimal(r1)
    k2=Decimal(1.0)/Decimal(r2)
    k3=Decimal(1.0)/Decimal(r3)
    k4=k1+k2+k3+2*(k1*k2+k2*k3+k3*k1).sqrt()
    r4=Decimal(1.0)/Decimal(k4)
    print r4
0
jfs On

If more iterations should yield better results then you could ignore input t parameter and iterate until result converges within current precision:

import decimal

#NOTE: separate user input from the algorithm
#      no input inside `radius()` function
def radius(r1, r2, r3):
    with decimal.localcontext() as ctx:
        ctx.prec += 2 # increase precision for intermediate calculations
        prev = None # previous value
        k1, k2, k3 = [1 / decimal.Decimal(r) for r in [r1, r2, r3]]
        while True: 
            # change some parameters to simulate converging algorithm
            #NOTE: you don't need to wrap anything using `Decimal()`
            k1 = k1 + k2 + k3 + 2*(k1*k2 + k2*k3 + k3*k1).sqrt()
            r = 1 / k1
            if prev == r: # compare using enhanced precision
                break
            prev = r # save previous value
    return +r # `+` applies current precision

decimal.getcontext().prec = 50 # set desired precision
print(radius(*map(int, raw_input().split())))

For a working example that demonstrates this technique, see Gauss-Legendre Algorithm in python that calculate Pi upto 100 digits.