Domanda

In this answer it is explained how to avoid args to be sorted in SymPy classes like Mul, Add and so on.

For a new created class like this one explained here it can go to the right hand side when multiplied by a sympy.core.numbers.Float, sympy.core.numbers.Pi or sympy.core.numbers.Integer, for example, giving:

print D(x) * 1.
1.0*D(x)

The original expression gives 0. when evaluated, while the new one gives D(x).

In order for this differential operator to work properly, it must stay on the left hand side:

print D(x) * 1.
D(x)*1.0

Is there any hidden parameter, like _op_priority for changing __mul__() priority, that tells SymPy the type that stays more to the left or to the right?

È stato utile?

Soluzione

Multiplication by a Mul does not work the way you expect it to.

First off, the printing order has nothing to do with anything. If that's all you care about, you can change it by modifying the printer.

You should instead look at the object's .args. But even here, this does not matter. When you multiply something by a multiplication, it does not "apply" each multiplication in the order it is seen. Rather, it creates a new Mul object with all the args combined (to be sure, in the commutative=False case, the args are kept in order). Mul does not call any special submethods on these objects. This is a feature we want (see https://code.google.com/p/sympy/issues/detail?q=1941&id=1941 and https://github.com/sympy/sympy/wiki/Canonicalization), but for now, it is not done.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top