davidedc / Algebrite

Computer Algebra System in Javascript (Typescript)
http://algebrite.org
MIT License
955 stars 59 forks source link

quote evaluates some expressions #141

Closed sformichella closed 3 years ago

sformichella commented 3 years ago

The quote function evaluates expressions like 2 * 2, 10 / 5, and x + x to 4, 2, and 2x, respectively. This seems to be a bug since the documentation describes quote as not evaluating the expression passed to it. Expressions like 2 + 2 and 4 - 3 are not evaluated as expected: quote(2 + 2) = "2 + 2", quote(4 - 3) = "4 - 3".

davidedc commented 3 years ago

Hi @sformichella - quote is tricky, there are two overlapping reasons for the confusing results:

  1. test quote by doing print(quote(x+x)) rather than quote(x+x) - this is because the "javascript" print might do some beautifications and evaluations of its own, while the "algebrite" print doesn't. This might be a separate issue of its own but it doesn't concern quote.

  2. there are two parse-time simplifications that happen (search for parse_time_simplifications) i.e. numeric constants are multiplied right away and "1*" is taken away. Try to disable that flag and see if it all works better for you - but I think there might be some code that "trusts" that there is a normal form to expressions whereby we never want constants multiplications (makes handling of expressions easier to normalise them that way), so check to see if it works for you.

Commented runs: print(quote(1+1)) -> 1+1 print(quote(2*2)) -> 4 // numeric constants are multiplied away at parse time print(quote(10/5)) -> 2 // numeric constants are multiplied away at parse time print(quote(x+x)) -> x+x print(quote(x*x)) -> x*x // not a constant print(quote(2*x)) -> 2*x print(quote(1*x)) -> x // 1* is simplified at parse time

Hope it makes sense. Closing for now.

davidedc commented 3 years ago

by the way note that "simplify_1_in_products" is done after "multiply_consecutive_constants"... which is strange because it would seem that the first is a sub-case of the second. However It could be that you want to simplify the "1*" but not do the "other" simplification.

davidedc commented 3 years ago

also see the comment at the top of the lookup code if you use quote a lot, as it explains some of the tricks needed to actually "make use" of quote

sformichella commented 3 years ago

Great! Thank you :)