Michał S
Michał S

Reputation: 21

Python SymPy weird expression result

import sympy
import math
from sympy import *
a, b, c, d, stf, lc = symbols('a b c d stf lc')
init_printing()
expr = (2*(sin (a) + sin (b)/2)*(sin (c) + sin (d)/2)*stf)+(2*(cos (a) + cos (b)/2)*(cos (c)+ cos (d)/2)*lc)*2
expr

when I run this ine ig gives me as result: 2*lc*(2*cos(a) + cos(b))(cos(c) + cos(d)/2) + stf(2*sin(a) + sin(b))*(sin(c) + sin(d)/2)

I realize that first formula in expr is not the simplest, but when I try to only print it out, it makes some weird simplification. when I substiute all variables and print it out again, it goes even further: (2sin(30)+sin(40))(250sin(30)+500sin(60))+(cos(40)+2cos(30))(5000cos(60)+2500cos(30))

is there any option to make SymPy not to change the order of elements in formula and just print it out in nice latex and then substiute variables and print again but keeping order of all elements from first formula? I don't want to call any kind of simplification, at least not yet, as this formula is simple enough.

Upvotes: 1

Views: 150

Answers (1)

Jeffrey Hall
Jeffrey Hall

Reputation: 51

The order of the elements that is printed is the order in which it is stored -- and because the operator "+" is commutative by fiat, you can't specify an order for them to be printed.

For multiplication and multiplicative operators, you can specify that the indeterminate are non-commutative; e.g.

A,B = symbols('A B', commutative=False)

B*A
# B*A

A*B
# A*B

What you want to keep in mind is that, when you type something like "a+b" in the REPL loop, the interpreter creates a new object with a SymPy class, evaluates the expression "a+b", and sets the created object to the result of that evaluation. What is being stored isn't the formula "a+b", but an object that represents the mathematical object that "a+b" represents. Likewise, if you type:

a = 3 + 4

a is set to 7, not to the "formula" 3+4.

On the other hand, if you do not want to actually evaluate the expression, or want to keep track of its original string form, you can use the UnevaluatedExpr property:

from sympy import UnevaluatedExpr

UnevaluatedExpr( A ) + UnevaluatedExpr( B )
# A + B

UnevaluatedExpr( B ) + UnevaluatedExpr( A )
# B + A

Be careful though:

UnevaluatedExpr( A + B)
# A + B

UnevaluatedExpr( B + A)
# A + B

Upvotes: 2

Related Questions