Skip to content

Commit

Permalink
Merge pull request #123 from ChristopherChudzicki/no-vec-triple-mult
Browse files Browse the repository at this point in the history
disallow multiplication of 3+ vectors w/o parens
  • Loading branch information
jolyonb authored Aug 8, 2018
2 parents c111aa2 + 40aa3f4 commit 283ca12
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
6 changes: 6 additions & 0 deletions mitxgraders/helpers/calc/calc.py
Original file line number Diff line number Diff line change
Expand Up @@ -958,6 +958,12 @@ def eval_product(self, parse_result):
Traceback (most recent call last):
CalcError: Unexpected symbol + in eval_product
"""
num_vectors = sum([isinstance(operand, MathArray) and operand.ndim == 1
for operand in parse_result])
if num_vectors >= 3:
raise CalcError("Multiplying three or more vectors is ambiguous. "
"Please place parentheses around vector multiplications.")

result = parse_result[0]
data = parse_result[1:]
while data:
Expand Down
24 changes: 23 additions & 1 deletion tests/helpers/calc/test_calc_arrays.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import numpy as np
from mitxgraders import evaluator, MathArray
from mitxgraders.helpers.calc.math_array import equal_as_arrays
from mitxgraders.helpers.calc.exceptions import UnableToParse
from mitxgraders.helpers.calc.exceptions import UnableToParse, CalcError

def test_array_input():
"""Test that vectors/matrices can be inputted into calc.py"""
Expand Down Expand Up @@ -54,3 +54,25 @@ def test_math_arrays():
expr = '(z*[[1, 5], [4, -2]]^n + 10*A/x)*v'
result = evaluator(expr, variables, max_array_dim=2)[0]
assert equal_as_arrays(result, (z*A**n + 10*A/x)*v)

def test_triple_vector_product_raises_error():
# Since vector products are interpretted as dot products, they are
# ambiguous, and we disallow them.

variables = {
'i': MathArray([1, 0]),
'j': MathArray([0, 1]),
}

assert equal_as_arrays(
evaluator("(i*i)*j", variables)[0],
variables['j']
)

match = ("Multiplying three or more vectors is ambiguous. "
"Please place parentheses around vector multiplications.")
with raises(CalcError, match=match):
evaluator("i*i*j", variables)[0]

with raises(CalcError, match=match):
evaluator("i*2*i*3*j", variables)[0]

0 comments on commit 283ca12

Please sign in to comment.