casting - Setting uniform Numpy dtype of all scalars and arrays (how to avoid downcasting in precision) -


question: simplest way set dtype of all scalar , array variables using numpy?

problem: size , complexity of algorithms grow, finding difficult tracing convergence problems due round-off , truncation errors. need way confidently set precision of operations eliminate errors trivial cause.

specifics: indicated in research section, having difficult time figuring out how set precision type of scalars variable (see below). though arrays have variable dtype, because scalar may not have been explicitly set same or higher precision dtype, down-casting occurs , lose precision unknowingly in algorithms.

research:

can set float128 standard float-array in numpy question gave me great advice; set array dtype variable , in code define variable "numpy.float64" or whatever want. but, how scalars?

how perform precise calculations in python, regardless of input types? 1 suggests mapping scalars desired input. but, there cleaner way?

what have been doing (thanks ophion in comment below):

import numpy np prec = np.float96  # simple example of scalar might end in code some_val = 5.0 - 3.99999999999999999992  # current way of casting dtype of scalars dtype of arrays myscalar = np.array(some_val, dtype=prec)  # suggestion of using mapping: myscalar = map(prec, (dt,))[0] 

as following works well:

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

it might simplest write shorthand definition convert you:

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

or

quad=np.float128 

just double check:

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

you creating 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 () 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -