bexi
bexi

Reputation: 105

Square root to 50 decimal places without importing decimal or math function

Is it possible to calculate to 50 decimal places without having to use the decimal import? The below prints what I want but I would like to know how to do it without any math or decimal import.


def sqrt2(num, P):
    decimal.getcontext().prec = P + len(str(num)) + 2
    x = decimal.Decimal(num)
    y = decimal.Decimal(1)
    e = decimal.Decimal(10) ** decimal.Decimal(-P)
    while (x - y >= e):
        x = (x + y) / 2
        y = num / x

    
print (sqrt2(2, 50)) 

I also tried:

    x=n
    y=1.000000 
    e=0.000001 
    while x-y > e:
        x=(x+y)/2
        y=n/x
    print (x)

n = 2
squareRoot(n)

s = squareRoot(n)
a = format(s, ".2f")
print (s)

But got the error message "unsupported format string passed to NoneType"

Upvotes: 0

Views: 332

Answers (1)

STerliakov
STerliakov

Reputation: 7858

First thing you should mention is that your sqrt function does not return any value. So None is returned. Just add the line

return(x)

to the end of function definition and better remove line print(x) too to make your function return the value instead of printing it.

But the question is deeper. First of all, mention, that float length in python 3 (built-in) is only approx. 16 decimal digits after point. So we can`t calculate more precisely. There are modules which can allow you doing that: numpy supports float128 (approx. 32 decimal digits), if that's not enough - have a look at Decimal or mpmath. Both are well-documented and support higher precision. There's no built-in method.

An article about high-precision calculations in python and reasons why they are required: https://habr.com/ru/post/305276/

Upvotes: 1

Related Questions