Click here to Skip to main content
15,886,755 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The result is:
1.4142135623730951
1.41421356237309504880168872420969807856967187537694807317667973799073247846210703 => reference
SQRT OVER

only 16 decimals long and the last digit is also wrong (1 instead of zero)

What I have tried:

I tried this code:

Python
from math import sqrt

def main():
    n = '2.0'
    root2th = sqrt(float(n))
    print(root2th)
    print('1.41421356237309504880168872420969807856967187537694807317667973799073247846210703', '=> reference')

if __name__ == '__main__':
    main()
    print('SQRT OVER')
Posted
Updated 1-Jan-23 5:06am
v3
Comments

1 solution

While I have no expirience in Python, a short google lead me to this:
from math import sqrt
# loading decimal library
from decimal import *

def main():
    n = '2.0'
    a = Decimal(2)
    root2th = sqrt(float(n))
    print(root2th)
    print(a.sqrt())
    print('1.41421356237309504880168872420969807856967187537694807317667973799073247846210703', '=> reference')

if __name__ == '__main__':
    main()
    print('SQRT OVER')


The result is:
1.4142135623730951
1.414213562373095048801688724
1.41421356237309504880168872420969807856967187537694807317667973799073247846210703 => reference
SQRT OVER


[Edit]
Arbitrary presicion, see line getcontext().prec = 80

from math import sqrt
# loading decimal library
from decimal import *

def main():
    n = '2.0'
    getcontext().prec = 80
    a = Decimal(2)
    root2th = sqrt(float(n))
    print(root2th)
    print(a.sqrt())
    print('1.41421356237309504880168872420969807856967187537694807317667973799073247846210703', '=> reference')

if __name__ == '__main__':
    main()
    print('SQRT OVER')
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900