simona
simona

Reputation: 2181

higher precision in python

I am running some python v3.3.2 scripts that use numpy and scipy and math. I am suspecting that there is an issue of numerical precision in my computation, and I would like to increase the precision in some particular modules that I have written and see if it makes a difference in the final result. In my module I am using some algebraic manipulations and numpy.sqrt.

How do I manipulate the precision of the computations in a module that is already written by me?(I can modify it). I have seen that there are several modules available like decimal and mpmath and bigfloat, and I was trying to figure out from the documentation which one would be more suitable for my task. The first one is already installed and I should install the other two. Ideally I would like to write a command on the top of the module and specifying the precision that I need in that module, does something like that exist?

EDIT ---------

I think the problem may come from computation of second derivative:

def secondderivative(x,y):
  xl     = np.roll(x,1) # x1
  xr     = np.roll(x,-1)# x3
  yl     = np.roll(y,1)
  yr     = np.roll(y,-1)

  ind    = np.where(np.isnan(y) | np.isnan(yl) | np.isnan(yr) )[0]

  deriv2 = (2 * yl / ((x - xl)  * (xr - xl))
        - 2 * y  / ((xr - x)  * (x - xl))
        + 2 * yr / ((xr - xl) * (xr - x)))

  for i in ind:
    deriv2[i] = np.nan

  deriv2[0]             = np.nan
  deriv2[len(deriv2)-1] = np.nan
  return deriv2

I have seen the result from gradient is completely different:

np.gradient(np.gradient(y,x),x)

Upvotes: 1

Views: 2174

Answers (1)

sascha
sascha

Reputation: 33522

When your code is based on numpy/scipy and co., you can only use the types supported by these libs. Here is the overview.

The paragraph Extended precision will be relevant for you.

Combining numpy/scipy with decimal, mpmath and co. would need a lot of work (in the general case)!

It would have been much more wise to show some code so that one could guess what's going on. Even with limited precision, there are techniques which makes a difference: e.g. iterative-refinement in solving linear systems.

Upvotes: 2

Related Questions