Question

Question: What is the simplest way to set the dtype of all scalar and array variables using numpy?

Problem: As the size and complexity of my algorithms grow, I am finding it very difficult tracing convergence problems due to round-off and truncation errors. I need a way to confidently set precision of all operations to eliminate those errors as a trivial cause.

Specifics: As indicated in the research section, I am mainly having a difficult time figuring out how to set the precision type of scalars to be variable (see below). Even though my arrays have variable dtype, because a scalar may not have been explicitly set to the same or higher precision dtype, down-casting occurs and I lose the precision unknowingly in my algorithms.

Research:

Can i set float128 as the standard float-array in numpy This question gave me great advice; always set the array dtype to a variable and in your code define that variable as "numpy.float64" or whatever you want. But, how to do this for scalars?

How to perform precise calculations in Python, regardless of input types? This one suggests mapping my scalars to the desired input. But, is there a cleaner way?

What I have been doing is this (thanks to Ophion in his comment below):

import numpy as np
prec = np.float96

# a simple example of a scalar that might end up in my code
some_val = 5.0 - 3.99999999999999999992

# my current way of casting dtype of my scalars to the dtype of my arrays
myscalar = np.array(some_val, dtype=prec)

# the suggestion of using mapping:
myscalar = map(prec, (dt,))[0]
Was it helpful?

Solution

As the following works well:

>>> a=np.float128(5)
>>> a.dtype
dtype('float128')
>>> b=a-9
>>> b.dtype
dtype('float128')

It might be simplest to write a shorthand definition that will convert this for you:

def quad(num):
    return np.float128(num)

or

quad=np.float128

Just to double check:

>>> c=quad(5)-quad(4)
>>> c.dtype
dtype('float128')
>>> c
1.0

You are creating a zero-d numpy array:

>>> c.flags
  C_CONTIGUOUS : True
  F_CONTIGUOUS : True
  OWNDATA : True
  WRITEABLE : False
  ALIGNED : True
  UPDATEIFCOPY : False
>>> np.isscalar(c)
True
>>> c.shape
()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top