0

I'm trying to plot an array of points onto a SymPy graph of x^2*sin(x)*cos(x) but I don't know how to do it. My array of points is a list of the Newton's method evaluation of the function guess = [1.63334806538257, 1.57496329804422, 1.57081816486420, 1.57079632740207, 1.57079632679490, 1.57079632679490], obviously I'll need the y-coordinates too but what I'm really looking for is how to graph a list in this library.

Alternatively, I used Matplotlib for this function, which is my intended result, but Matplotlib has trouble converting the user input string to a function. If it's possible to do it using Matplotlib that'll also be good.

The code for the above image is

 def str_to_func(string):
    return lambda x: eval(string)
function = str_to_func(s)
yy = [function(x) for x in guess]

xx = np.linspace(-10, 10, 100)
y = [function(i) for i in xx]

plt.figure(figsize=(8,6), dpi=100)
plt.plot(guess, yy, 'x', label = "Iterated points", color = "black")
plt.plot(xx, y, label = f"${sm.latex(f)}$", color = "blue")


plt.title(f"Newton-Raphson Method evaluation of ${sm.latex(f)}$")

plt.xlabel("$x$") 
plt.ylabel("$f(x)$")

plt.legend(loc="best")
plt.axhline(y=0, color='k', linewidth = 0.5)
plt.axvline(x=0, color='k', linewidth = 0.5)


plt.grid(True)

This throws the error "unsupported operand type(s) for ^: 'Float' and 'float'",

I've tried writing the full expression (x**2*sin(x)*cos(x)), without the "^", since I thought that was the problem, but that doesn't work.

This is my first post so apologies for anything I've missed.

1 Answers1

1

Sympy's plot accepts an argument markers= to add e.g. colored markers. The ^ symbols means xor in Python, so it needs to be converted. (Note that the guesses are extremely close together.)

from sympy import sympify, plot

string = 'x^2*sin(x)*cos(x)'
func = sympify(string, convert_xor=True)

guess = [1.63334806538257, 1.57496329804422, 1.57081816486420, 1.57079632740207, 1.57079632679490, 1.57079632679490]
guess_y = [func.subs('x', g).evalf() for g in guess]

plot(func, xlim=(-1, 2), ylim=(-1, 1), markers=[{'args': [guess, guess_y, 'ro']}])

sympy plot with markers

JohanC
  • 71,591
  • 8
  • 33
  • 66