0

So, I'm making a program that calculates the roots of a function using the bisection method and then graphs it, highlighting the roots. I've been having problems in that last step, since I don't know how to mark the roots no matter the function.

My code:

import mylibrary as bib
import matplotlib.pyplot as plt
import numpy as np

def function(x):
     
    y = (x*x/2.0)-2
    
    return y

x = np.linspace(-3,3,100)
y = function(x)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
plt.title("(x^2)-2")
plt.plot(x,y)
plt.show()

Which outputs the function.

I'd like to know a way to always have the roots (already calculated) also appear on the plot.

Bonus question: Can I make the title be the funtion being calculated automatically, too?

  • `ax.scatter([root1, root2], [0, 0], s=100, color='red', alpha=0.5)`. By the way, it is recommended to use `ax.set_title(...)` and `ax.plot(..)` instead of `plt.plot`. See [matplotlib's object-oriented interface](https://matplotlib.org/matplotblog/posts/pyplot-vs-object-oriented-interface/). Automatically setting this type of title isn't supported. You might also be interested in [sympy](https://docs.sympy.org/latest/modules/plotting.html). Note that your title is different from your function. – JohanC Dec 16 '21 at 23:09

0 Answers0