1
xvals = linspace(a, b, 1001)
expr = //string taken as input
yvals=list()
for x in xvals:
    y=eval(expr)
    yvals.append(y)
plt.plot(xvals, yvals)

This works fine for any polynomial function But gives error in case of sin(x) or log(x) : name 'sin(x)' is not defined How to resolve this?

suman
  • 57
  • 8
  • What are your inports? Is `linspace` from `numpy` – hpaulj Feb 08 '21 at 06:32
  • Does this answer your question? [Python eval function with numpy arrays via string input with dictionaries](https://stackoverflow.com/questions/25826500/python-eval-function-with-numpy-arrays-via-string-input-with-dictionaries) Also you could have a look at sympy for advanced symbolic calculations. – v.tralala Feb 10 '21 at 05:27

1 Answers1

1

Importing the math module should work:

from math import *
import numpy as np

xvals = np.linspace(0, pi, 5 )
expr = "sin(x)"
yvals=list()
for x in xvals:
    y=eval(expr)
    yvals.append(y)

print(yvals)
#[0.0, 0.7071067811865475, 1.0, 0.7071067811865476, 1.2246467991473532e-16]

Keep in mind you can use eval with any function, e.g.:

my_func = lambda x: x/3 + 1
eval("my_func(9)")
#4.0

So, importing all functions from math solves the problem.

Pablo C
  • 4,661
  • 2
  • 8
  • 24