Home > Enterprise >  How to manage undefined variables in a calculation
How to manage undefined variables in a calculation

Time:09-28

I have some predefined variables and some preexisted formulas(all multiplications). Formulas are calculating as expected besides when any of the variables are not defined. Knowing that my formulas only handle multiplications I was thinking to give the value =1 to any undefined variable, in that way the calculation does break.

Is there any way to loop through the formulas, isolate the undefined variables and give them a value =1?

In the example below, ‘k’ is not defined and this calculation(kbd=kbd) is generating an error

#defined variables
a=10
b=5
c=3
d=6
e=7
f=2
g=9

#preexisted formulas
abc=a*b*c
fed=d*e*f
efg=e*f*g
kbd=k*b*d


NameError                                 Traceback (most recent call last)
<ipython-input-10-f9e3059809fc> in <module>
----> 1 kbd=k*b*d

NameError: name 'k' is not defined

CodePudding user response:

You can use something like this:

a=10
b=5
c=3
d=6
e=7
f=2
g=9

formulas = ['a*b*c','d*e*f','e*f*g','k*b*d']

for form in formulas:
    variables = form.split('*')
    for v in variables:
        if v not in locals():
            locals()[v]=1
        
    eval(form)

CodePudding user response:

Sympy is made for addressing your title 'How to manage undefined variables in a calculation'. The variables can be defined as Sympy symbols:

from sympy import *
from sympy.abc import a, b, c, d, e, f, g, k
# alternative of above line `a, b, c, d, e, f, g, k=symbols('a b c d e f g k')`
a=10
b=5
c=3
d=6
e=7
f=2
g=9

abc = a*b*c 
fed = sympify(d*e*f) #you can convert an arbitrary expression to a type that can be used inside SymPy, based on https://docs.sympy.org/latest/modules/evalf.html; not really necessary for these multiplication examples
efg=e*f*g 
kbd = k*b*d 
print(N(abc)) #based on https://docs.sympy.org/latest/modules/evalf.html
print(abc)
print(fed) #based on https://docs.sympy.org/latest/modules/evalf.html
print(fed.evalf()) #based on https://docs.sympy.org/latest/modules/evalf.html
print(kbd)
print(simplify(kbd)) # based on https://www.tutorialspoint.com/sympy/sympy_simplification.html
kbd # - or `simplify(kbd)` - as last line in a Jupyter cell, you'll see fancy `30k` with `k` in italics in out cell.

That last line won't do anything in a script though, yet the output will look fancy in a Jupyter cell using the Python kernel where you've run %pip install sympy in the cell above. (You can try that in the cell of a Jupyter notebook here.)

Output from the print commands:

150.000000000000
84
84.0000000000000
30*k
30*k

Seen in 'Out' cell if run in Jupyter:

30           
  • Related