The precision of mpmath.sqrt(2) is not what I expected. What am I doing wrong?
import mpmath as mp
mp.prec = 20
mp.nprint(mp.sqrt(2), 20)
result: 1.4142135623730951455
expected: 1.4142135623730950488
(according to this reference)
import mpmath as mp
mp.prec = 20
mp.nprint(mp.sqrt(2), 20)
result: 1.4142135623730951455
expected: 1.4142135623730950488
(according to this reference)
mp.prec
is the binary precision. mp.dps
is the decimal one.
In [588]: mpmath.mp.dps=20
In [589]: mpmath.sqrt(2)
Out[589]: mpf('1.4142135623730950488011')
With this setting:
In [590]: print(mpmath.mp)
Mpmath settings:
mp.prec = 70 [default: 53]
mp.dps = 20 [default: 15]
mp.trap_complex = False [default: False]
cf with the default
Mpmath settings:
mp.prec = 53 [default: 53]
mp.dps = 15 [default: 15]
mp.trap_complex = False [default: False]
Interesting case. Using pythons Decimal
it gives the same result as the reference you listed, but using float
or math.sqrt()
seems to give a different result.
>>> from decimal import Decimal
>>> '{:.25f}'.format(2**0.5) # Result 1
'1.4142135623730951454746219'
>>> '{:.25f}'.format(math.sqrt(2)) # Result 1
'1.4142135623730951454746219'
>>> '{:.25f}'.format(math.sqrt(Decimal('2'))) # Result 1
'1.4142135623730951454746219'
>>> '{:.25f}'.format(Decimal('2') ** Decimal('0.5')) # Result 2
'1.4142135623730950488016887'
# The reference you listed # Result 2
'1.4142135623730950488016887'
Your library is probably using float
internally.
But I think this is normal and NOT a bug, since float
s are not meant to be 100% precise; they are meant to be fast on the machine.