latexify_py icon indicating copy to clipboard operation
latexify_py copied to clipboard

n+1-1 in sum/prod

Open odashi opened this issue 3 years ago • 5 comments

Currently the analyzer of sum and prod does not recognize the reducable addition and subtraction in the stop parameter of range:

It would be good if we could get $n$ rather than $n+1-1$ in most cases. This reduction would be safe because the operands of range must be integers, whose objects must be always associative and commutative in terms of operations $+$ and $-$.

odashi avatar Nov 03 '22 18:11 odashi

Note that in general arithmetic is not associative even if all operands are numbers. For example:

So this treatment is available only when the function always takes integers.

odashi avatar Nov 03 '22 19:11 odashi

Implemented here:

https://github.com/google/latexify_py/blob/c6c291d3bcce28a269d175be384ab955ac2100c8/src/latexify/codegen/function_codegen.py#L335-L354

Current behavior is caused by not being able to convert n+1 to a numeric type.

The n+1 case can perhaps be treated as a special case since it is the most common but a more general solution might be preferred. Since reduction is only needed for n+x or n-x maybe we can explicitly check for these two cases.

Casper-Guo avatar Nov 09 '22 21:11 Casper-Guo

@Casper-Guo I think the code above is an obsolete permalink. In the current implementation, FunctionCodegen introduced an additional analyzer that obtains subtree of range:

https://github.com/google/latexify_py/blob/071a12d06ae67c578f92f973945c0067b3f4976d/src/latexify/codegen/function_codegen.py#L334

We can implement a specific process if we detected range_info.stop is BinOp and the operator is Add or Sub.

odashi avatar Nov 10 '22 01:11 odashi

We would like to work on this. Can you please assign me and @lakeblair.

Casper-Guo avatar Nov 10 '22 02:11 Casper-Guo

@Casper-Guo Thanks for taking your effort! Assigned to you anyway since you are the only person who attended this discussion.

odashi avatar Nov 10 '22 03:11 odashi

Resolved by #115

odashi avatar Nov 28 '22 08:11 odashi