karlsalame
karlsalame

Reputation: 59

Number eval issue python

I want to evaluate the following differential using the values in list y however I cant figure out what I am doing wrong. I am supposed to get 1.9256 for y=5, 1.9956 for y=10 and 2.1356 for y=20. What I'm trying to do is ask the user to input an equation with x as its variable, derive this equation with respect to x, ask the user to input as many values as he wants and evaluate the expression using these inputted values. Thanks for your help.

import sympy as sym
print('Sensitivity: ')
#exp = input('Enter the expression to find the sensitivity: ')
exp='(0.007*(x**2))+(1.8556*x)-1.8307'
#values=list(map(float,input('Enter the values at which you want to compute the sensitivity seperated by spaces: ').split())) 
values=[5,10,20]
x=sym.Symbol('x')      
differential=str(sym.diff(exp,x))
print(differential)
for i in y:
    expression=differential.replace(str(x),str(values))
    value=eval(expression)
    print('The sensitivity at',i,'is: ',value)

Upvotes: 0

Views: 49

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295403

What I believe you intended to write is:

import sympy as sym

exp='(0.007*(x**2))+(1.8556*x)-1.8307'
values=[5,10,20]
x=sym.Symbol('x')      
differential=str(sym.diff(exp,x))
print(differential)
for value in values:
    expression=differential.replace(str(x),str(value))
    result=eval(expression)
    print('The sensitivity at',value,'is: ',result)

...which emits as output:

The sensitivity at 5 is:  1.9256
The sensitivity at 10 is:  1.9956
The sensitivity at 20 is:  2.1356

Note the changes:

  • We're iterating for value in values -- values exists, y does not.
  • We're assigning the eval result to a separate variable (in this case, result)

This still is not by any means good code. Good code would not do string substitution to substitute values into code. Substituting repr(value) instead of str(value) would be at least somewhat less broken.

Upvotes: 1

Related Questions