b3m2a1 / mathematica-PyTools

A framework for working with python from Mathematica
https://www.wolframcloud.com/objects/b3m2a1.paclets/PacletServer/main.html#PyTools
MIT License
6 stars 2 forks source link

Incorrect behaviour of `ToSymbolicPython` #2

Open bgatessucks opened 6 years ago

bgatessucks commented 6 years ago

I think there are missing parenthesis in the conversion of Mathematica expressions to Python, and this alters the result due to the precedence of algebraic operations. Examples using Mathematica 11.3 and PyTool 1.0.9s:

ToSymbolicPython[2 (2 z1^2 - 1)] // ToPython
(* 2*2*z1**2+-1 *)
(1)/(z3 Sqrt[z4 + z5]) /. {z3 -> 2., z4 -> 1.2, z5 -> 3.4}
(* 0.233126  *)

ToSymbolicPython[Evaluate[(1)/(z3 Sqrt[z4 + z5]) ]] // ToPython
(* "z3**-1*z4+z5**-1/2" *)

ExternalEvaluate["Python", "
 z3=2.;
 z4=1.2;
 z5=3.4;
 print(z3**-1*z4+z5**-1/2, z3**-1*(z4+z5)**-1/2, z3**-1*(z4+z5)**-0.5)
 "]
(* (0.7470588235294118, 0.05434782608695653, 0.23312620206007845) *)

Notice that the output of ToSymbolicPython[...] // ToPython contains expressions such as 1/2 which would return 0 when evaluated in Python.

b3m2a1 commented 6 years ago

@bgatessucks I think I was a bit stingy with parens when implementing. I'll just put everything in parens and then later come back and potentially apply some post-processing to get rid of unnecessary ones. I'll give that a patch. For the second issue, the behavior I have in is correct for python3, which is my default python. It also better agrees with the Mathematica code. 1/2. should be use for the approximate value and 1/2 for the exact one, which has a different interpretation in python2 and python3

bgatessucks commented 6 years ago

Thanks. I got past that by using a wrapper for expressions like Times and Power, then I undid it on the python side.