0

For a college assignment, I've been tasked to get the square root of a number to 100 decimal places I've found an easy way of getting the square root, but the output only goes as far as 52 decimal places before defaulting to outputting zeroes i.ie

def sqrt2():
    #if x**y == x to the power of y (or y times multiplication of x e.g. 2**3 == 2*2*2) then to calculate the square root change y to 1/2
    #e.g if 4 to the power of 2 == 16 then 16 to the power of 1/2 = 4 
    result = 2**(0.5)
    printResult = format(result, ',.100f')
    
    print(printResult)

sqrt2()

The output of this is 1.4142135623730951454746218587388284504413604736328125000000000000000000000000000000000000000000000000 so as you can see it defaults to zeroes around half way through the number. I understand why Python won't do more decimal places as its just an approximation https://docs.python.org/3.4/tutorial/floatingpoint.html Any way of making the result more accurate without using any imports/libraries etc.?

  • 1
    Does this answer your question? [how can i show an irrational number to 100 decimal places in python?](https://stackoverflow.com/questions/4733173/how-can-i-show-an-irrational-number-to-100-decimal-places-in-python) – Chris Oct 10 '20 at 15:45
  • 2
    Multiply your number by `10**200` and use Newton's method to get the integer square root. Then insert a decimal point in the right place. – Mark Ransom Oct 10 '20 at 15:49
  • How do you just insert a decimal in the correct place though? – Dylan Creaven Oct 10 '20 at 15:55
  • @Chris all the answers on that question require an import or library. Don't know why you'd try to solve the problem the hard way when libraries are so easily available, but it's not my question. – Mark Ransom Oct 10 '20 at 16:04
  • @DylanCreaven the square root of `10**200` is `10**100`, so you just put the decimal place in front of the right-most 100 digits. – Mark Ransom Oct 10 '20 at 16:05
  • Also, even though you were able to print 52 digits you'll find that not more than 17 of them are accurate. The rest are essentially noise. – Mark Ransom Oct 13 '20 at 16:05

0 Answers0