예제 #1
0
def test_summation():
    grader = SumGrader(answers={
        'lower': '0',
        'upper': '1',
        'summand': 'x',
        'summation_variable': 'x'
    },
                       input_positions={'summand': 1})

    # Here we bypass the class entirely to just test the summation capabilities.

    def summand(x):
        return x

    assert 6 == grader.perform_summation(summand, lower=1, upper=3, even_odd=0)
    assert 9 == grader.perform_summation(summand, lower=1, upper=5, even_odd=1)
    assert 6 == grader.perform_summation(summand, lower=1, upper=5, even_odd=2)
    assert 1e3 * (1e3 + 1) / 2 == grader.perform_summation(summand,
                                                           lower=1,
                                                           upper=float('inf'),
                                                           even_odd=0)

    def summand(x):
        return x**2

    assert 14 == grader.perform_summation(summand,
                                          lower=1,
                                          upper=3,
                                          even_odd=0)
예제 #2
0
def test_convergence():
    # Test that we get convergence to well-known functions
    # Here we bypass the class entirely to just test the summation capabilities.
    grader = SumGrader(answers={
        'lower': '0',
        'upper': '1',
        'summand': 'x',
        'summation_variable': 'x'
    },
                       input_positions={'summand': 1})

    x = 0.1

    def exp_summand(n):
        value, _ = evaluator('x^n/fact(n)', {'n': n, 'x': x})
        return value

    result = grader.perform_summation(exp_summand,
                                      lower=0,
                                      upper=float('inf'),
                                      even_odd=0,
                                      infty_val=100)
    expect = np.exp(x)
    assert abs(result - expect) < 1e-14

    def sin_summand(n):
        value, _ = evaluator('(-1)^((n-1)/2)*x^n/fact(n)', {'n': n, 'x': x})
        return value

    result = grader.perform_summation(sin_summand,
                                      lower=0,
                                      upper=float('inf'),
                                      even_odd=1,
                                      infty_val=100)
    expect = np.sin(x)
    assert abs(result - expect) < 1e-14

    def cos_summand(n):
        value, _ = evaluator('(-1)^(n/2)*x^n/fact(n)', {'n': n, 'x': x})
        return value

    result = grader.perform_summation(cos_summand,
                                      lower=0,
                                      upper=float('inf'),
                                      even_odd=2,
                                      infty_val=100)
    expect = np.cos(x)
    assert abs(result - expect) < 1e-14