I want to graph a function of number of divisors using numpy. But there is a problem with np.arange
import matplotlib.pyplot as plt
import numpy as np
def f(t):
num_of_divisors = 0
for i in np.arange(1, t+1):
if t % i == 0:
num_of_divisors += 1
return num_of_divisors
t2 = np.arange(1, 100, 1)
plt.figure()
plt.plot(t2, f(t2), color='black')
plt.show()
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I tried but it was a ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Amantai Asanbekov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
You have to vectorize your function.
Since it is inherently iterative, you cannot replace is easily with pure numpy code. A workaround is to use numpy.vectorize
:
@np.vectorize
def f(t):
num_of_divisors = 0
for i in np.arange(1, t+1):
if t % i == 0:
num_of_divisors += 1
return num_of_divisors
Output: