【发布时间】:2021-02-13 23:37:21
【问题描述】:
所以我得到了一个由一个类和三个方法组成的程序。这三种方法是函数导数的三种不同数值近似。现在我已经实现了函数中需要的函数 f、x 值和 h 值。当我要绘制这些图时,我在图中一无所获。此外,当我打印不同的实例时,我只会得到三个相同值的数组
[5.87785252 5.87785252 5.87785252]
我不知道该类是否存在固有问题,或者我是否遗漏了代码中的某个地方,但有人可以帮我解决这个问题吗?
我的完整代码:
import matplotlib.pyplot as plt
import numpy as np
class Diff:
#constructor taking f as an argument
def __init__(self,f):
self.f=f
#method for first approximation
def diff1(self,x,h):
self.f=f
self.x=x
self.h=float(h)
return (f(x+h)-f(x))/h
#method for second approximation
def diff2(self,x,h):
self.f=f
self.x=x
self.h=float(h)
return (f(x+h)-f(x-h))/2*h
#method for third approximation
def diff3(self,x,h):
self.f=f
self.x=x
self.h=float(h)
return (-f(x+2*h)-8*f(x+h)-8*f(x-h)+f(x-2*h))/12*h
h=[0.9,0.6,0.3,0.1]
x=np.linspace(-1,1,3)
def f(x):
return np.sin(2*np.pi*x)
Derivative=Diff(f)
Exact=2*np.pi*np.cos(2*np.pi*x)
for h in h:
Derivative1=Derivative.diff1(x,h)
plt.plot(Derivative1,Exact)
plt.show()
【问题讨论】:
-
self.f=f,不是说f=self.f吗? -
不,这是正确的语法
-
self.f=f只能在__init__方法中 -
哦,是的,这是真的,我只看到了第一个。
-
对多个事物使用一个名称是有风险的。在
self.f=f中,那个f是您定义的def f()函数,不一定是在初始化程序中传递的f。将该函数重命名为def sin_func(x),您的程序将停止工作。
标签: python class object methods