Harold Ship
Harold Ship

Reputation: 1019

Numpy function to check `>=0` with tolerance for floating point error

Using numpy, our optimization solver has a function that checks the feasibility of a solution by computing the slacks for the constraints, in the form of matrices and vectors.

We test feasibility using code such as:

    return np.all(slacks_x >= 0) and np.all(slacks_u >= 0)

This has a bug, because sometimes the slacks can take values like -1.5 e-12 i.e. close to zero but negative due to floating point errors. In this case it erroneously returns False.

Is there a function in numpy that can check >=0 with tolerances? Current workaround is to check >= -0.1.

Upvotes: 2

Views: 784

Answers (1)

FBruzzesi
FBruzzesi

Reputation: 6495

Maybe try to use machine epsilon np.finfo(np.float32).eps or np.finfo(np.float64).eps, and then return something like:

eps = np.finfo(np.float32).eps #np.finfo(np.float64).eps
return np.all(slacks_x >= -eps) and np.all(slacks_u >= -eps)

Upvotes: 3

Related Questions