0

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)

Bobby
  • 1,585
  • 3
  • 19
  • 42

2 Answers2

1

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]
hpaulj
  • 221,503
  • 14
  • 230
  • 353
0

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 floats are not meant to be 100% precise; they are meant to be fast on the machine.

Ralf
  • 16,086
  • 4
  • 44
  • 68
  • But mpmath was implemented for specifically managing arbitrary precision floating point, and I thought it should return the accurate representation of the digits(accuracy over speed)... Tnx for the reply :-) – Stolcius Von Stolcenberg Apr 27 '19 at 13:49