Skip to content

BUG: ufuncs that call into Python do not ignore FPEs e.g. for inf - inf #21416

@Steven-R-Hall

Description

@Steven-R-Hall

Describe the issue:

I'm writing a program that uses the casadi module to automatically differentiate Python expressions. The program constructs a numpy ndarray (with dtype='O') of objects with the casadi SX data type. Say the array is called 'x'. When performing arithmetic operations on the array, sometimes a Numpy warning is generated. For example,

>>> 2**31  /  x

generates the warning

RuntimeWarning: invalid value encountered in true_divide

and

>>> 2**31 + x

generates the warning

RuntimeWarning: invalid value encountered in add

Despite the warning, the correct value is produced. However, the following code runs without warning:

>>> (2**31-1)  /  x
>>> (2**31-1)  +  x

My expectation is that

>>> numpy.true_divide(y, x)

should run without a warning whenever y is a float or int, x is a numpy.ndarray with dtype='O', and y/x[i] can be calculated without warning for all values of i in range. But that is not what happens here. Curiously, it fails only when the integer or float is at least 2 **31, even though no such behavior exists in casadi (or at least not obviously).

The sample code below is the simplest code that demonstrates the issue. It seems that the line calculating y2 should never generate a warning if the line calculating y1 does not.

Reproduce the code example:

import numpy as np
import casadi as cd

x = np.zeros([1], dtype='O')
x[0] = cd.SX.sym('r')  # only element of array x is a casadi symbol

y1 = 2 ** 31 / x[0]  # no warning or error generated
y2 = 2 ** 31 / x  # generates warning, but result should be np.array([y1], dtype='O')
y3 = (2 ** 31 - 1) / x  # ... but this works fine with no warning or error

Error message:

true_divide_problem.py:8: RuntimeWarning: invalid value encountered in true_divide
  y2 = 2 ** 31 / x  # generates warning, but result should be np.array([y1], dtype='O')

NumPy/Python version information:

1.21.4 3.9.9 (main, Nov 30 2021, 10:15:14)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions