numpydecimalprecision

get float64 for numpy calculation


def chi2_distance(a,b):
   
    d=1-(np.dot(a,b)/(norm(a,axis=1)*norm(b)))
      
    return d

a and b are float32 and have max 8 decimals. but i want the calculation has 16 decimals accuracy.

a.shape is r*n and b shape is (n,)

i did this :

def chi2_distance(a,b):
    a = a.astype(np.float64)
    b = b.astype(np.float64)
    d=1-(np.dot(a,b)/(norm(a,axis=1)*norm(b)))
      
    return d

now the d.dtype is float64 but i still get 8 decimal accuray in results!!


Solution

  • @hpaulj answered correctly. Simply when you put for the function output tolist(), it can show 16 decimals which is 64 bit for 64bit computer processors. Weirdly apparently numpy can not show more than 32 bit, but when you convert the numpy to a list it can show 16 decimals instead. The code is below:

    import numpy as np
    from numpy.linalg import norm
    def chi2_distance(a,b):
      a = a.astype(np.float64)
      b = b.astype(np.float64)
      d=(1-(np.dot(a,b)/(norm(a,axis=1)*norm(b)))).tolist()
      
      return d
    k=np.array([[8.34567,2,4],[10000.99887,6,7]])
    kk=np.array([100.3456,200,300])
    print(k.shape)
    print(kk.shape)
    hh=chi2_distance(k,kk)
    print(hh)