Evaluate as many parameters as possible (SymPy)

399 Views Asked by At

I have this code in SymPy:

from sympy import *
par_amplitude, par_const_force = symbols('Delta_U f')
equation = par_amplitude * par_const_force
print(equation.evalf(subs={'f':3, 'Delta_U':2}))

The output is obviously 6.

My problem occurs when I have access to only one parameter, like so:

print(equation.evalf(subs={'Delta_U':2}))

Instead of expected 2 * f I get Delta_U * f.

What am I doing wrong? Is there a way to evaluate an expression, where not all parameters are available?

EDIT:

Yes, I am after a mixed numerical/symbolic output. Imagine a situation where there is a lot of parameters (generated automatically, so you're not even sure how many), and there is a function supplying all the subs values. If you were to miss just one substitution value, you get basically nothing out of evalf.

2

There are 2 best solutions below

0
On

You can substitute in your symbolic expression before evaluating numerically:

print(equa.subs({'Delta_U':2}))
print(equa.subs({'Delta_U':2}).evalf())

Substitution also yields 6 even without numerical evaluation:

print(equa.subs({'Delta_U':2, 'f':3}))

EDIT: I have an idea why evalf(...) will not return 2*f. I assume that evalf tries to only return completely numerical result, but 2*f is clearly something mixed. A numerical 2 and a symbolic f.

2
On

This is a known issue and there is discussion about it here.