简体   繁体   English

sympy 不忽略指数表达式中不重要的小数

[英]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.我有一个计算一些数学方程的代码,当我想查看简化的结果时,它不能将2.02内部幂等同起来,这是合乎逻辑的,因为一个是浮点数,另一个是整数。 But decision was sympys where to put these two values, not mine.但是决定是把这两个值放在哪里,而不是我的。

Here is the expression in my results that sympy is not simplifying这是我的结果中 sympy 没有简化的表达

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.我正在寻找一种方法让 sympy 假设除符号之外的所有内容都是浮点数,并阻止它决定哪个是浮点数或整数。

this problem has been asked before by Gerardo Suarez but not with a satisfactory answer. Gerardo Suarez之前曾问过这个问题,但没有得到满意的答复。

There is another sympy function you can use called nsimplify .您可以使用另一个名为nsimplify sympy 函数。 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:更新正如@Shoaib Mirzaei 提到的,您还可以像这样在simple simplify()函数中使用rational参数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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