简体   繁体   English

如何不重复计算 sympy 数字

[英]How to not double count sympy numbers

I need for a project to calculate some sort of simplicity of some expressions and among other things I need to assign to each number appearing in the expression a complexity (something like log2(x), such that the complexity is measured in bits, ie log2(4)=2 bits).我需要一个项目来计算某些表达式的某种简单性,除此之外,我需要为表达式中出现的每个数字分配一个复杂性(类似于 log2(x),这样复杂性以位为单位,即 log2 (4)=2 位)。 Anyway, for a give sympy expression I have this piece of code:无论如何,对于一个给予 sympy 表达我有这段代码:

is_atomic_number = lambda expr: expr.is_Atom and expr.is_number
eq_numbers = [subexpression for subexpression in preorder_traversal(expr) if is_atomic_number(subexpression)] 

It mainly works, but if I have something of the form 2*(x+y), that returns as the numbers appearing in the expression (2,2) instead of just 2, which is what I want.它主要有效,但是如果我有 2*(x+y) 形式的东西,它会返回出现在表达式 (2,2) 中的数字,而不仅仅是 2,这正是我想要的。 Is there a way to make sure that when something gets factored out, I count it only once?有没有办法确保当某些东西被分解时,我只计算一次? Thank you!谢谢!

The atoms method might be what you want: atoms方法可能是您想要的:

>>> (2*(x+y)).atoms(Number)
{2}

The replace method has the option too keep track of the mapping used, but it doesn't handle identical items that were replaced by different values replace方法也有跟踪使用的映射的选项,但它不处理被不同值替换的相同项目

>>> (2*x + x**2).replace(lambda x:x.is_Number, lambda x: Dummy(), map=True)
(Dummy_1*x + x**Dummy_2, {2: Dummy_2})

So the following might work:所以以下可能有效:

>>> def flatargs(expr):
...     if expr.is_Atom: yield expr
...     else:
...         for a in expr.args:
...             for i in flatargs(a): yield i
>>> list(flatargs(2*x+x**2))
[x, 2, 2, x]
>>> from sympy.utilities.iterables import multiset
>>> multiset([i for i in flatargs(2*x+x**2+y/2) if i.is_Number)
{1/2: 1, 2: 2}

If you want the numerator and denominator separately from flatargs you would have to handle the Rational atom as a special case and deal with the cases when numerator or denomitor is 1. But hopefully what is here will get you on your way.如果您希望将分子和分母与flatargs分开, flatargs必须将 Rational 原子作为特殊情况处理,并处理分子或分母为 1 的情况。但希望这里的内容可以帮助您。

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

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