HAECHANG YUN
HAECHANG YUN

Reputation: 21

I'm trying to approximate the square root of 2 in python

here is the code i wrote. my idea is put a number(between 0~9) at the end of x and square it and then see if it's smaller than 2 ,choosing the biggest

x = 1.4



for n in range(21):
    next_num = [0,1,2,3,4,5,6,7,8,9]
    candidate = []
    for number in next_num:
        if float(str(x)+str(number))*float(str(x)+str(number))<2:
            candidate.append(number)
            
    x = float(str(x)+str(max(candidate)))
    

print(x)

but the problem is i only get 1.414213562373 this much 13 digits i tried typing in bigger number in range but i only get this

thank you

Upvotes: 2

Views: 621

Answers (2)

The64mer7
The64mer7

Reputation: 1

You can approximate any root with integers so you won't be limited by decimal places, but the only down side is that your output won't have decimal point.

"x" is the number you want to take root of. "b" is the nth root. "dec" is the number of decimal places.

def root(x,b,dec):
    s = 0
    n = 0
    for q in range(dec):
        for k in range(10):
            s = n
            n = 10*n+(9-k)
            if(n**b > x*10**(q*b)):
                n = s
            else:
                break
    return n

Input:
root(2,2,500)

Output:
14142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927557999505011527820605714701095599716059702745345968620147285174186408891986095523292304843087143214508397626036279952514079896872533965463318088296406206152583523950547457502877599617298355752203375318570113543746034084988471603868999706990048150305440277903164542478230684929369186215805784631115966687130130156185689872372

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336448

floats don't have sufficient precision for this. You need the decimal module:

from decimal import Decimal, getcontext
getcontext().prec = 51 # the "1" before the decimal point counts, too
x = Decimal("1.4")
for n in range(50):
    next_num = [0,1,2,3,4,5,6,7,8,9]
    candidate = 0
    for number in next_num:
        if Decimal(str(x)+str(number))*Decimal(str(x)+str(number))<2:
            candidate = number
    x = Decimal(str(x)+str(candidate))

print(x)

Output:

1.414213562373095048801688724209698078569671875376946

Upvotes: 3

Related Questions