这是我的第一个代码,使用numpy.linspace方法:
import numpy as np
import matplotlib.pyplot as plt
def graph(formula, string, x1, x2):
x = np.linspace(x1, x2)
y = formula(string, x)
plt.plot(x, y)
def my_formula(string, x):
return eval(string)
graph(my_formula, "2 * (x ** 3) - 9.5 * (x ** 2) + 10.5 * x", 0, 3)
plt.tight_layout()
plt.show()
然而,如果我这样做,它可以很好地工作,而不是导入numpy:
import matplotlib.pyplot as plt
class Module:
@staticmethod
def linspace(finish, slices, start=0):
each = float((finish - start) / (slices - 1))
res = list()
for i in range(slices):
res.append(start + i * each)
return res
def graph(formula, string, x1, x2):
x = Module.linspace(x2, 50, start=x1)
y = formula(string, x)
plt.plot(x, y)
def my_formula(string, x):
return eval(string)
graph(my_formula, "2 * (x ** 3) - 9.5 * (x ** 2) + 10.5 * x", 0, 3)
plt.tight_layout()
plt.show()
出现一个错误:
Traceback (most recent call last):
File "C:/Users/QINY/PycharmProjects/begin/covid/seven.py", line 24, in <module> graph(my_formula, "2 * (x ** 3) - 9.5 * (x ** 2) + 10.5 * x", 0, 3)
File "C:/Users/QINY/PycharmProjects/begin/covid/seven.py", line 16, in graph y = formula(string, x) File "C:/Users/QINY/PycharmProjects/begin/covid/seven.py", line 21, in my_formula return eval(string)
File "<string>", line 1, in <module> TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
有人能解释一下numpy.adarray是如何自动迭代列表的吗?
它们使用标准运算符作为函数。
它们的类型支持__pow__
、__mul__
、__add__
等功能。实现方式可以对ndarray
的每个元素应用操作(非常有效…(
您可以创建自己的继承自list
的类型,并让它实现这些成员函数,自己迭代列表,将其应用于每个元素。