Skip to content

Instantly share code, notes, and snippets.

@mukaschultze
Created July 24, 2020 21:53
Show Gist options
  • Save mukaschultze/956e3cc4883251bb01bfb07b9bc44fd6 to your computer and use it in GitHub Desktop.
Save mukaschultze/956e3cc4883251bb01bfb07b9bc44fd6 to your computer and use it in GitHub Desktop.
Plot Graph
import re
import numpy as np
from matplotlib import pyplot as plt
replacements = {
'sin' : 'np.sin',
'cos' : 'np.cos',
'exp': 'np.exp',
'sqrt': 'np.sqrt',
'^': '**',
}
allowed_words = [
'x',
'sin',
'cos',
'sqrt',
'exp',
]
def string2func(string):
''' evaluates the string and returns a function of x '''
# find all words and check if all are allowed:
for word in re.findall('[a-zA-Z_]+', string):
if word not in allowed_words:
raise ValueError(
'"{}" is forbidden to use in math expression'.format(word)
)
for old, new in replacements.items():
string = string.replace(old, new)
def func(x):
return eval(string)
return func
if __name__ == '__main__':
func = string2func(input('enter function: f(x) = '))
a = float(input('enter lower limit: '))
b = float(input('enter upper limit: '))
x = np.linspace(a, b, 250)
plt.plot(x, func(x))
plt.xlim(a, b)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment