Reputation: 688
I am writing a script in which I am trying to handle different numbers appearing in a sympy expression. In order to extract what I need I am using something similar to this: isinstance(expr, sympy.numbers.Float)
, which checks if a number appearing in my expression is a float. This works quite well for most numbers (floats, integers and rational numbers). However I am having some issues with negative numbers. For example if I do this:
eq = parse_expr("cos(2*a)+cos(0.5*b)")
srepr(eq)
I get this output:
Add(cos(Mul(Integer(2), Symbol('a'))), cos(Mul(Float('0.5', precision=53), Symbol('b'))))
which says that I have an integer, 2 and a float 0.5, which is what I need. However if I do this:
eq = parse_expr("cos(-2*a)+cos(0.5*b)")
srepr(eq)
I get this output:
Add(cos(Mul(Integer(2), Symbol('a'))), cos(Mul(Float('0.5', precision=53), Symbol('b'))))
so basically the minus sign is ignored. Why is this the case and how can I make it keep the minus sign and output something of the form Integer(-2)
instead of Integer(2)
?
Thank you!
Upvotes: 0
Views: 947
Reputation: 3586
It is not ignored, it has been simplified. Recall that cosine function is an even function, that is f(-x)=f(x).
Let me illustrate what happens if it is an odd funciton instead.
>>> from sympy import *
>>> eq = parse_expr("cos(-2*a)+cos(0.5*b)")
>>> srepr(eq)
"Add(cos(Mul(Integer(2), Symbol('a'))), cos(Mul(Float('0.5', precision=53), Symbol('b'))))"
>>> eq = parse_expr("sin(-2*a)+cos(0.5*b)")
>>> srepr(eq)
"Add(Mul(Integer(-1), sin(Mul(Integer(2), Symbol('a')))), cos(Mul(Float('0.5', precision=53), Symbol('b'))))"
In the final line, when it is an sine rather than cosine, we do get a -1.
Remark: This is the outcome if we set the evaluate parameter to be False.
>>> eq = parse_expr("sin(-2*a)+cos(0.5*b)", evaluate = False)
>>> srepr(eq)
"Add(Mul(Integer(-1), sin(Mul(Integer(-2), Integer(-1), Symbol('a')))), cos(Mul(Float('0.5', precision=53), Symbol('b'))))"
Upvotes: 6