Reputation: 41
I'm trying to implement a code for the following function: f(x) = sen(2πx), x ∈ [0, 2], to get the graph of it. But I'm getting the return that the sine is not defined. I'm not quite understanding what I would have to correct. I would be grateful if someone can help me
Code I used:
import math
import numpy as np
import matplotlib.pyplot as plt
def f(x): return sin*(2*np.pi*x)
x = np.linspace(0,2)
plt.plot(x, f(x))
plt.grid()
plt.show()
This was the only code I thought of to solve this issue, because I thought it would print correctly and without errors
Upvotes: 1
Views: 2782
Reputation: 15525
There are two distinct ways to get access to function sin
from module numpy
:
Either:
from numpy import sin
sin([3,4,5])
# array([ 0.14112001, -0.7568025 , -0.95892427])
Or:
import numpy as np
np.sin([3,4,5])
# array([ 0.14112001, -0.7568025 , -0.95892427])
You got an error because you tried a mix of both.
Upvotes: 0
Reputation: 664
The problem is that you are trying to use the sin
function without import it. You can find the function in the numpy
package:
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return np.sin(2*np.pi*x)
x = np.linspace(0,2)
plt.plot(x, f(x))
plt.grid()
plt.show()
Upvotes: 1
Reputation: 538
Because the sine function is defined inside numpy, so you should explicitly specify the library where the function is defined:
def f(x): return np.sin*(2*np.pi*x)
Upvotes: 1