Skip to content

Make numpy ufunc work with ufloat #344

@ikondov

Description

@ikondov
  • Versions:
    python == 3.10.12
    numpy == 2.2.6
    uncertainties == 3.2.3

  • Code to reproduce / observed behavior:

In [1]: import numpy

In [2]: from uncertainties import ufloat

In [3]: numpy.exp(ufloat(1., 0.1))
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
AttributeError: 'Variable' object has no attribute 'exp'

The above exception was the direct cause of the following exception:

TypeError                                 Traceback (most recent call last)
Cell In[3], line 1
----> 1 numpy.exp(ufloat(1., 0.1))

TypeError: loop of ufunc does not support argument 0 of type Variable which has no callable exp method
  • Expected behavior: Calling an ufunc from numpy should have similar behavior as calling the same function from uncertainties.unumpy:
In [4]: from uncertainties import unumpy

In [5]: unumpy.exp(ufloat(1., 0.1))
Out[5]: array(2.718281828459045+/-0.27182818284590454, dtype=object)
  • Motivation: using uncertainties with other packages (for example pint) will be facilitated enormously, for example to call numpy.exp(pint.Quantity(ufloat(1., 0.1))) using this basic example. Of course, it would be nice if all numpy ufuncs and numpy functions work in this way. Currently, I have to maintain some custom fragile code to use numpy ufuncs and numpy functions with the two packages.

  • Suggested solutions: one possible way is maybe to define some special methods in the uncertainties.core.Variable class to point to the custom unumpy implementations. This seems to work in pint.Quantity.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions