0

When asking for a symbol .free_symbols I get something in curly braces (which is a set).

If I use this set as list of arguments for lambdify of sympy it seems it is converted into a list. This is hinted in the doc but I suggest a warning to be given here when this conversion is made. A good reason for this is that the ordering of the symbols may be altered in this conversion.

In my case _chiSquare.free_symbols gives {c_95_0, c_95_1} but list({'c_95_0', 'c_95_1'}) gives ['c_95_1', 'c_95_0']

I like to automate the making of numerical functions using .free_symbols but this is hard to work with if order of variable is changed without notice.

My question is how one is supposed to deal with free_symbols and lambdify in a way that arguments order is kept fixed.

Rho Phi
  • 1,182
  • 1
  • 12
  • 21

1 Answers1

0

I think it is better to keep track of the symbols explicitly rather than using free_symbols.

If you must work from free_symbols then you can sort them to get a consistent ordering:

In [3]: sorted((x*y).free_symbols, key=lambda s: s.name)
Out[3]: [x, y]
Oscar Benjamin
  • 12,649
  • 1
  • 12
  • 14
  • just to clarify, I am generating my symbols with `sp.symarray` so that the routine can work with functions in `$R^n$` for any $n$, so the explicit tracking is kind of against the purpose. I had missed I can specify the `key` in `sorted` to the `name` attribute. Thanks – Rho Phi Jul 08 '20 at 19:08
  • You can get the ordered list of symbols from the symarray with `list(array.flat)` – Oscar Benjamin Jul 09 '20 at 09:22
  • just to clarify, the symarray is not available in this application. I have a sympy object as the object returned by a function. The symarray is created in the function, so it is lost outside of it. I only have the sympy expression and need to figure out how to turn it into a function that can be evaluated efficiently numerically for plots, minimization and things like that. – Rho Phi Jul 10 '20 at 13:32