简体   繁体   中英

sympy not ignoring unimportant decimals in exponential expression

I have a code that calculate some mathematical equations and when I want to see the simplified results, it can not equate 2.0 with 2 inside power, which is logical since one is float and the other is integer. But decision was sympys where to put these two values, not mine.

Here is the expression in my results that sympy is not simplifying

from sympy import *

x = symbols('x')

y = -exp(2.0*x) + exp(2*x)
print(simplify(y)) # output is -exp(2.0*x) + exp(2*x)

y = -exp(2*x) + exp(2*x)
print(simplify(y)) # output is 0

y = -2.0*x + 2*x
print(simplify(y)) # output is 0

y = -x**2.0 + x**2
print(simplify(y)) # output is -x**2.0 + x**2

is there any way working around this problem? I am looking for a way to make sympy assume that everything other than symbols are floats, and preventing it to decide which one is float or integer.

this problem has been asked before by Gerardo Suarez but not with a satisfactory answer.

There is another sympy function you can use called nsimplify . When I run your examples they all return zero:

from sympy import *

x = symbols("x")

y = -exp(2.0 * x) + exp(2 * x)
print(nsimplify(y))  # output is 0

y = -exp(2 * x) + exp(2 * x)
print(nsimplify(y))  # output is 0

y = -2.0 * x + 2 * x
print(nsimplify(y))  # output is 0

y = -(x ** 2.0) + x ** 2
print(nsimplify(y))  # output is 0

Update As @Shoaib Mirzaei mentioned you can also use the rational argument in the simplify() function like this:

simplify(y,rational=True)

You could make a custom function to pre-filter everything. I think this is quite simple and can be done like this:

def is_number(n):
    try:
        float(n)   

    except Exception:
        return False
    return True

def type_fixer(x: str):

    if is_number(x):
        return float(x)
    
    else:
        return x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM