Commit ac2867e6 authored by Adam Blank's avatar Adam Blank
Browse files

Update test_estimation.py

parent 373c84a8
No related merge requests found
Showing with 41 additions and 15 deletions
+41 -15
from decimal import Decimal from decimal import Decimal
from sympy import series, atan, nsimplify, diff from sympy import series, atan, nsimplify, diff
from sympy.calculus.util import Interval, maximum from sympy.calculus.util import Interval, maximum
import math from math import floor, factorial
from src.taylor import arctan from src.taylor import arctan
import pytest import pytest
...@@ -12,20 +11,47 @@ def term(N, xval, a): ...@@ -12,20 +11,47 @@ def term(N, xval, a):
ivl = Interval(xval - 0.001, a + 0.001) + Interval(a - 0.001, xval + 0.001) ivl = Interval(xval - 0.001, a + 0.001) + Interval(a - 0.001, xval + 0.001)
d = diff(atan(x), x, N + 1) d = diff(atan(x), x, N + 1)
M = maximum(d, x, ivl) M = maximum(d, x, ivl)
return nsimplify(abs(((M * ((x - a)**(N + 1))/math.factorial(N + 1)).subs(x, xval)))) return nsimplify(abs(((M * ((x - a)**(N + 1))/factorial(N + 1)).subs(x, xval))))
def ref_taylor(f, a, N, xval): def ref_taylor(f, a, N, xval):
return nsimplify(series(f, x=x, x0=a, n=N).removeO().subs(x, xval).doit()) return nsimplify(series(f, x=x, x0=a, n=N).removeO().subs(x, xval).doit())
def approx_atan(N, xval, a): EPSILON = 0.0001
return ref_taylor(atan(x), a, N, xval), term(N, xval, a)
def approx_atan(N, xval):
@pytest.mark.parametrize('q', range(20)) if floor(xval) == 0:
def test_arctan(q): return ref_taylor(atan(x), 0, N, xval), term(N, xval, 0)
xval = q / 10 else:
_, error = approx_atan(10, xval, 0) _, center_error = approx_atan(N, floor(xval) - EPSILON)
v, e = arctan(Decimal(xval)) return ref_taylor(atan(x), floor(xval), N, xval), center_error + term(N, xval, floor(xval) - EPSILON)
if xval < 0.9:
assert 0 <= float(e) - float(error) < 0.003 @pytest.mark.parametrize('xval', [x/10 for x in range(20)])
assert abs(math.atan(xval) - float(v)) <= float(e) def test_arctan(xval):
print('testing', xval)
ref_val1, ref_error = approx_atan(10, xval)
ref_val1 = float(ref_val1)
ref_error = float(ref_error)
ref_val2 = atan(xval)
our_val, our_error = arctan(Decimal(xval))
our_val = float(our_val)
our_error = float(our_error)
errors_diff = our_error - ref_error
error_with_ref1 = abs(ref_val1 - our_val)
error_with_ref2 = abs(ref_val2 - our_val)
epsilon = 0.15
if xval < 0.5:
epsilon = 0.001
elif xval < 1.0:
epsilon = 0.05
assert 0 <= errors_diff < epsilon
assert error_with_ref1 <= our_error
assert error_with_ref2 <= our_error
assert abs(error_with_ref2 - our_error) < epsilon
if __name__ == "__main__":
test_arctan(0.0)
test_arctan(0.5)
test_arctan(0.9)
test_arctan(1.0)
test_arctan(1.5)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment