4

I tried to get sqrt value of a long int

from math import sqrt
print sqrt(410241186411534352) 

<< 640500731.0

It returned 640500731.0, which indeed is 640500730.999999993... in precision. How to fix that?

I solved it according to @DSM and @Rob's reply, thank you so much.

from math import sqrt
from decimal import Decimal
print Decimal(410241186411534352).sqrt() 
蒋艾伦
  • 464
  • 1
  • 5
  • 16
  • If you need an integer sqrt function, see [this question](http://stackoverflow.com/questions/15390807/integer-square-root-in-python) for several options. – DSM Mar 29 '13 at 02:10

2 Answers2

5
>>> import decimal
>>> decimal.getcontext().prec = 100
>>> a=decimal.Decimal(410241186411534352)**decimal.Decimal(.5)
>>> print a
640500730.9999999929742468943411712910588335443486974564849183256021518032770726219326459594197730639
>>> print a*a
410241186411534352.0000000000000000000000000000000000000000000000000000000000000000000000000000000000
>>> 
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
2

Python math library functions are thin wrappers around the C math library functions, so Python is converting the long integer into a double-sized floating point number before doing the computation. If you want genuine multiprecision arithmetic in Python, you could try mpmath.

Simon
  • 10,679
  • 1
  • 30
  • 44