Yousef Kaddoura
Yousef Kaddoura

Reputation: 33

Not able to plot a function

So I am having a problem plotting an if statement function. Could someone tell me where i am going wrong? The code follows:

import numpy as np
import matplotlib.pyplot as plt 



#x-axis

x_1 = np.arange(-20,20,0.001)

#defining the function
def h(x):
    """
    input: x \in R
    oupit: h(x) defined above in R. 
    """
    if x == 0:
        return 1
    else:
        return np.sin(x)/x

def g(x):
    """
    input: x \in R
    oupit: g(x) defined above in R. 
    """
    return np.cos(x)

#drawing the function

plt.plot(x_1,h(x_1),label = r"$\frac{\sin(x)}{x}$",color="red")
plt.legend()
plt.plot(x_1,g(x_1),label = r"$\cos(x)$",color="blue")
plt.legend()
plt.grid(linestyle="dotted")
plt.ylabel("$f(x)$")
#plt.savefig('img231.pdf')
plt.show()

The main problem is probably in the line with plt.plot(x_1,h(x_1)). Any answers are appreciated:)~ Thanks, Y

Upvotes: 0

Views: 416

Answers (1)

JohanC
JohanC

Reputation: 80279

To write an if-test in numpy, you need np.where: np.where(x == 0, 1, np.sin(x)/x). This still will write a warning for division by zero, which can be suppressed using with np.errstate(divide='ignore').

Also note that np.arange(-20, 20, 0.001) generates 40000 values, which is quite high compared to the number of pixels on a screen (an even compared to the dots on a printer). Using np.linspace() you have easier control over the number of points used. Using too many points can unnecessarily slow down calculations and plotting.

Calling plt.legend() twice can be a bit confusing. The second call will remove the first legend.

import numpy as np
import matplotlib.pyplot as plt

x_1 = np.linspace(-20, 20, 1000)

def h(x):
    with np.errstate(divide='ignore'):
        return np.where(x == 0, 1, np.sin(x) / x)

def g(x):
    return np.cos(x)

plt.plot(x_1, h(x_1), label=r"$\frac{\sin(x)}{x}$", color="crimson")
plt.plot(x_1, g(x_1), label=r"$\cos(x)$", color="cornflowerblue")
plt.grid(linestyle="dotted")
plt.ylabel("$f(x)$")
plt.legend()
plt.show()

resulting plot

Upvotes: 3

Related Questions