Skip to content

Commit

Permalink
analytical and partial derivatives test
Browse files Browse the repository at this point in the history
  • Loading branch information
jagerber48 committed Jul 18, 2024
1 parent d7ee99b commit b841984
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 10 deletions.
43 changes: 34 additions & 9 deletions tests/test_core_new.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
from math import sqrt, sin, cos
import math

import pytest

from uncertainties.core_new import UFloat, ToUFuncPositional
from uncertainties import umath_new
from uncertainties.core_new import UFloat, ToUFunc, ToUFuncPositional

from helpers import ufloats_close


repr_cases = cases = [
(UFloat(10, 1), 'UFloat(10.0, 1.0)'),
Expand Down Expand Up @@ -50,9 +54,9 @@ def test_unary(
(20 + x, 30, 1),
(-20 + x, -10, 1),
(20 * x, 200, 20),
(x + y, 30, sqrt(2**2 + 1**2)),
(x * y, 200, sqrt(20**2 + 20**2)),
(x / y, 0.5, sqrt((1/20)**2 + (2*10/(20**2))**2)),
(x + y, 30, math.sqrt(2**2 + 1**2)),
(x * y, 200, math.sqrt(20**2 + 20**2)),
(x / y, 0.5, math.sqrt((1/20)**2 + (2*10/(20**2))**2)),
]


Expand Down Expand Up @@ -107,10 +111,13 @@ def test_not_equals(first, second):
assert first != second


usin = ToUFuncPositional((lambda x: cos(x),))(sin)
x = UFloat(10, 2)
usin = ToUFuncPositional((lambda t: math.cos(t),))(math.sin)
sin_cases = [
(usin(x), sin(10), 2 * cos(10))
(
usin(UFloat(10, 2)),
math.sin(10),
2 * math.cos(10),
),
]


Expand Down Expand Up @@ -152,4 +159,22 @@ def test_bool(unum: UFloat, bool_val: bool):

def test_negative_std():
with pytest.raises(ValueError, match=r'Uncertainty must be non-negative'):
unum = UFloat(-1.0, -1.0)
_ = UFloat(-1.0, -1.0)


func_derivs = ((k, v) for k, v in umath_new.deriv_dict.items())


@pytest.mark.parametrize("ufunc_name, ufunc_derivs", func_derivs)
def test_ufunc_analytic_numerical_partial(ufunc_name, ufunc_derivs):
if ufunc_name == "acosh":
# cosh returns values > 1
args = (UFloat(1.1, 0.1),)
elif ufunc_name == "atan2":
# atan2 requires two arguments
args = (UFloat(1.1, 0.1), UFloat(3.1, 0.2))
else:
args = (UFloat(0.1, 0.01),)
ufunc = getattr(umath_new, ufunc_name)
nfunc = ToUFunc(range(len(ufunc_derivs)))(getattr(math, ufunc_name))
assert ufloats_close(ufunc(*args), nfunc(*args), tolerance=1e-6)
2 changes: 1 addition & 1 deletion uncertainties/umath_new.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def log_der0(*args):
"acosh": ("1/math.sqrt(x**2-1)",),
"asinh": ("1/math.sqrt(1+x**2)",),
"atan": ("1/(1+x**2)",),
"atan2": ('x/(x**2+y**2)', "-y/(x**2+y**2)"),
"atan2": ('y/(x**2+y**2)', "-x/(x**2+y**2)"),
"atanh": ("1/(1-x**2)",),
"cos": ("-math.sin(x)",),
"cosh": ("math.sinh(x)",),
Expand Down

0 comments on commit b841984

Please sign in to comment.