Reputation: 1
I have been trying to plot the output of the function defined below,but not able to get the output. I tried several things but getting different errors every time. If somebody can help me with what it is that I am doing wrong, I shall be grateful.
import matplotlib.pyplot as plt
%matplotlib inline
import math
import sympy as sym
x = sym.symbols('x',positive = True)
lambd = 4
a= 3
def f(x):
return lambd**a * x**(a-1) * sym.exp(-lambd*x) / math.factorial(a-1)
x1 = np.linspace(0,1,10)
plt.plot(x1,f(x1))
In case I change the x1
as np.linspace(0,1,100)
then the error is
"ValueError: sequence too large; cannot be greater than 32"
What can be the reason for that? Some guidance in this will be highly appreciated.
Upvotes: 0
Views: 5565
Reputation: 339220
You're passing a numpy array x1
to a function f
. The problem that inside this function you have sympy.exp()
which does not understand what to do with an array, since it only works on symbols and numbers.
The easiest would be to use numpy.exp
instead.
import matplotlib.pyplot as plt
import numpy as np
import math
lambd = 4
a= 3
def f(x):
return lambd**a * x**(a-1) * np.exp(-lambd*x) / math.factorial(a-1)
x1 = np.linspace(0,1,10)
plt.plot(x1,f(x1))
plt.show()
If, for whatever reason, you need to use some function that only works on single numbers and not arrays, you can use numpy.vectorize
to convert the function to one that evaluates the input array elementwise.
import matplotlib.pyplot as plt
import sympy as sym
import numpy as np
import math
lambd = 4
a= 3
def f(x):
return lambd**a * x**(a-1) * sym.exp(-lambd*x) / math.factorial(a-1)
fv = np.vectorize(f)
x1 = np.linspace(0,1,10)
plt.plot(x1,fv(x1))
plt.show()
Upvotes: 2