How to plot two different functions in the same graph in Python

Viewed 124

I have this function:

from math import e

# f(x) = (e^3/3) - x
def ff(x):
    return e**((x**3)/3 - x)

This is how its plot looks like using this code:

x = np.linspace(-3, 2.5, 100)
y = ff(x)

plt.plot(x, y)
plt.grid()
plt.show()

enter image description here

I have this other graph that it's the result of the following code:

def euler(x0,y,a,b,step):
    listx = [x0]
    listy = [y]
    xn = x0
    yn = y
    
    while x0 < b: 
        y = y + step * f(x0, y)
        x0 = x0 + step
        
        if x0 > b:
            break
            
        listx.append(x0)
        listy.append(y)
        
    while xn > a:
        yn = yn - step * f(xn, yn)
        xn = xn - step
        
        if xn < a:
            break
        
        listx.append(xn)
        listy.append(yn)
        
    return listx, listy
x, y =  euler(step = 0.1, x0 = 0, y = 1, a = -3, b = 2.5)
plt.scatter(x, y, alpha = 0.5, s = 5)

plt.grid()
plt.xlim(-3, 2.5)
plt.show()

enter image description here

What I want to do is to plot both functions (euler and ff(x) functions) in the same graph. I've tried using the following code:

x, y =  euler(step = 0.1, x0 = 0, y = 1, a = -3, b = 2.5)
plt.scatter(x, y, alpha = 0.5, s = 5)

x2 = np.linspace(-3, 2.5, 100)
y1 = ff(x)
plt.scatter(x2, y1)

plt.grid()
plt.xlim(-3, 2.5)
plt.show()

But I got this error:

unsupported operand type(s) for ** or pow(): 'list' and 'int'

I would really appreciate your help.

1 Answers

From your code, do you mean y1=ff(x2)? If you want x, you may want y1=ff(np.array(x)), but then plot y1 against x

Related