how set numpy floating point accuracy?
In normal numpy use, the numbers are double. Which means that the accuracy will be less than 16 digits. Here is a solved subject that contains the same problematic ...
If you need to increase the accuracy, you can use symbolic computation .... The library mpmath ... is a quiet good one. The advantage is that you can use limitless precision. However, calculations are slower than what numpy can do.
Here is an example:
# The library mpmath is a good solution
>>> import sympy as smp
>>> import mpmath as mp
>>> mp.mp.dps = 50 # Computation precision is 50 digits
# Notice that the difference between x and y is in the digit before last (47th)
>>> x = smp.mpmath.mpf("0.910221324013388510820732335560023784637451171875")
>>> y = smp.mpmath.mpf("0.910221324013388510820732335560023784637451171865")
>>> x - y # Must be equal to 1e-47 as the difference is on the 47th digit
mpf('1.000014916280995001003481719184726944958705912691304e-47')
You can't do better with numpy. You can calculate exponentials with a better accuracy.
>>> smp.exp(x).evalf(20)
2.4848724344693696167
Note that for SymPy versions after 0.7.6, mpmath is no longer packaged with SymPy but is a dependency instead. This means that in newer SymPy versions sympy.mpmath
functions have moved to mpmath
.
Do you care about the actual precision of the result, or about getting the exact same digits back from your two calculations?
If you just want the same digits, you could use np.around()
to round the results to some appropriate number of decimal places. However, by doing this you'll only reduce the precision of the result.
If you actually want to compute the result more precisely, you could try using the np.longdouble
type for your input array, which, depending on your architecture and compiler, might give you an 80- or 128-bit floating point representation, rather than the standard 64-bit np.double
*.
You can compare the approximate number of decimal places of precision using np.finfo
:
print np.finfo(np.double).precision
# 15
print np.finfo(np.longdouble).precision
# 18
Note that not all numpy functions will support long double - some will down-cast it to double.
*However, some compilers (such as Microsoft Visual C++) will always treat long double
as synonymous with double
, in which case there would be no difference in precision between np.longdouble
and np.double
.