0

I'm trying to display a graph with a formula from the user using matplotlib in Python 3.6, but I'm having some problems. I tried

import numpy as np
import matplotlib.pyplot as plt

def graph(x_range):
    x = np.array(x_range)
    y = 2*x
    plt.plot(x, y)
    plt.show()

graph(range(-10, 11))

which works fine, but if I try replacing y = 2*x with y = input() and try inputting 2*x in the terminal, I get an error stating ValueError: Illegal format string "2*x"; two marker symbols

Any ideas as to how to fix this error, or is there a better way to graph a equation given by the user?

Thanks

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
HF1
  • 385
  • 1
  • 2
  • 14
  • 2
    There is no easy way to do what you want in python/numpy. Perhaps Sympy can be used? – DYZ Mar 25 '18 at 01:44
  • You'll have to build it. Check here: https://stackoverflow.com/questions/20748202/valueerror-malformed-string-when-using-ast-literal-eval – litepresence Mar 25 '18 at 02:29
  • 1
    I just decided to do what @DyZ said and use Sympy instead. Seems to be working perfectly fine now. Thanks! – HF1 Mar 25 '18 at 05:43

2 Answers2

0

Replace y=2*x with this

y = eval(input('Enter formula'))

However this is a very dirty shortcut.

hsnsd
  • 1,728
  • 12
  • 30
0

If you are looking for something fairly lightweight that "suits your situation" and doesn't evaluate "all mathematical expressions" then a whitelist method might serve you well

x = np.array(x_range)

print('equation types')
print('1) y=mx+b')
print('2) y=a*sin(b*(x+c))')
print('3) y=ax^2 + bx + c')
#...etc.

eq = int(input('equation type number: '))

if eq == 1:
    m = float(input('m'))
    b = float(input('b'))
    y = m*x+b
if eq == 2:
    #...etc.

plt.plot(x, y)
plt.show()
litepresence
  • 3,109
  • 1
  • 27
  • 35