lundi 31 août 2020

how to handle error in cauchy calculation in numpy

i want to calculate the Cauchy matrix with entries a_ij = 1/(x_i-y_j) for two vectors and using numpy

Example:
([1, 2], [3, 4]) --> [[-1/2, -1/3], [-1, -1/2]]

import numpy as np
    
    if len(y) != len(x) :
        raise ValueError ('len(x) and len(y) must be equal')
    else : 
        for i in range (len(x)) :
            for j in range (len(y)):
                if x[i] == y[j] :
                    raise ValueError('error')
                
                else : 
                    cauchym = 1.0/np.array([(x_i-y_j) for x_i in x for y_j in y]).reshape([len(x),len(y)])
                    return cauchym

My code seems to be working with regular input. However i get a few errors with input shown below and I don't know how to get around those

  1. array from difference length :

x = np.array([1, 2]) y = np.array([1.5, 2.5, 3.5, 5.0])

Error message : intro_numpy.py", line 82, in cauchy raise ValueError ('len(x) and len(y) must be equal') ValueError: len(x) and len(y) must be equal

  1. empty list : x = np.array([]) y = np.array([])** *Error message : Your result was in the wrong type:
  • You returned type: NoneType
  • Expected type: ndarray (from numpy)*
  1. 0 array :

x = np.array([0, 1, 2, 3, 4]) y = np.array([4, 3, 8, 1, 0])

error message : ValueError not raised* i don't understand why i need to raise a specific error for this one ? and if so which one

Thanks in advance for your suggestions , comments and advice

Aucun commentaire:

Enregistrer un commentaire