【问题标题】:How would I use two variables in a class with function requiring two variables?如何在需要两个变量的函数的类中使用两个变量?
【发布时间】: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


【解决方案1】:

您基本上是在尝试计算浮点数之后的这么多数字,而变量本身会混淆并显示完全不同的值。

你应该使用这些变量来解决问题:

np.double(num) #for 15 digit floating point presicion 
np.longdouble(num) #for 18 digit floating point precision

您还可以使用以下函数对变量进行四舍五入

np.round(num,d) #where d is the number of floating point digits left after rounding

另一个注意事项,你不应该使用与你的列表相同的变量来迭代它,这将在以后造成混乱 而不是:

for h in h:
    Derivative1=Derivative.diff1(x,h)

使用:

for point in h:
    Derivative1=Derivative.diff1(x,point)

【讨论】:

  • 错了。我仍然得到 [5.87785252 5.87785252 5.87785252] 作为我的打印件
  • 看不到图的原因是浮点精度。我建议您单独打印 Derivation1 的所有 3 个值。您会注意到实际值为: 5.877852522924731,5.877852522924731,5.877852522924738 并且是您的 diff 函数的实际结果
【解决方案2】:

问题

我对您的代码进行了一些修改,以下问题仅导致三个 价值观:

x = np.linspace(-1,1,3)

如果您查看 linspace (https://numpy.org/doc/stable/reference/generated/numpy.linspace.html) 的文档,您将看到两个位置参数(startstop),下一个可选参数是步数。使用您的代码,您的 linspace 的结果就是 [-1, 0, 1]。这不是需要 linspace 的东西,但它确实有效。

遍历 h

您可以将它们保存到数组中,而不是每次都将值保存在同一个变量中。像这样的:

Derivative1 = np.zeros((len(h), len(x)))

for idx, value in enumerate(h):
    Derivative1[idx]=Derivative.diff1(x,value)

之后你需要检查你的绘图函数,因为精确和这个数组不再匹配了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    • 1970-01-01
    • 2018-09-01
    • 2023-03-08
    相关资源
    最近更新 更多