diff --git a/uncertainties/test_umath.py b/uncertainties/test_umath.py index 83a8f89b..7263f396 100644 --- a/uncertainties/test_umath.py +++ b/uncertainties/test_umath.py @@ -341,3 +341,21 @@ def test_power_wrt_ref(): Checks special cases of the umath_core.pow() power operator. ''' test_uncertainties.power_wrt_ref(umath_core.pow, math.pow) + +def test_numpy_sqrt(): + ''' + Checks if numpys sqrt method works due to AffineScalarFunc having basic math + functions as members. + ''' + try: + import numpy + except ImportError: + import warnings + warnings.warn("Test not performed because NumPy is not available") + return + + a = ufloat(0.3, 0.01) + if not(numpy.sqrt(a) == umath_core.sqrt(a)): + raise Exception('Numpy sqrt (%s) and math sqrt (%s) do not match!' + % (numpy.sqrt(a), math.sqrt(a))) + diff --git a/uncertainties/umath_core.py b/uncertainties/umath_core.py index 64871445..4c11ca88 100644 --- a/uncertainties/umath_core.py +++ b/uncertainties/umath_core.py @@ -211,6 +211,8 @@ def _deriv_pow_1(x, y): 'tanh': [lambda x: 1-math.tanh(x)**2] } +make_an_attribute_of = ['sqrt'] + # Many built-in functions in the math module are wrapped with a # version which is uncertainty aware: @@ -261,6 +263,8 @@ def wrapped_func(*args, **kwargs): # !! The same effect could be achieved with globals()[...] = ... setattr(this_module, name, wraps(wrapped_func, func)) + if name in make_an_attribute_of: + setattr(AffineScalarFunc, name, wraps(wrapped_func, func)) many_scalars_to_scalar_funcs.append(name) diff --git a/uncertainties/unumpy/test_unumpy.py b/uncertainties/unumpy/test_unumpy.py index 1215c7eb..4be613ed 100644 --- a/uncertainties/unumpy/test_unumpy.py +++ b/uncertainties/unumpy/test_unumpy.py @@ -68,6 +68,8 @@ def test_numpy(): # TypeError (see PR #12700 in numpy repository) pass else: + # NOTE: if exp would be added as member method to AffineScalarFunc + # like sqrt already is, this would expectedly work raise Exception("numpy.exp unexpectedly worked") # Calculation of the mean, global and with a specific axis: @@ -329,3 +331,21 @@ def test_obsolete(): mat_obs = unumpy.umatrix.__call__(([1, 2], [1, 4])) # Obsolete call mat = unumpy.umatrix([1, 2], [1, 4]) assert arrays_close(mat_obs, mat) + +def test_numpy_linalg_norm(): + ''' + Checks if numpy.linalg.norm method works. + ''' + a = unumpy.uarray([3,4], [1,1]) + magnitude = unumpy.nominal_values(numpy.linalg.norm(a)) + if not(magnitude == 5): + raise Exception('numpy.linalg.norm([3,4]) does not return correct result!\n' + 'Expected 5, got %f' % magnitude) + + if not (numpy.linalg.norm(a) == numpy.sqrt(numpy.sum(numpy.power(a, 2)))): + raise Exception('numpy.linalg.norm(%s) does not return correct result!\n' + 'Expected %s, got %s' + % (a, + numpy.sqrt(numpy.sum(numpy.power(a, 2))), + numpy.linalg.norm(a))) +