从负值开始时列表索引错误

问题描述 投票:0回答:1

这段代码应该近似函数的值,只知道函数在某些任意点的值及其在所述点的导数。

这是代码:

class Expand:
    def __init__(self, fx: list, fy: list, dfy: list):
        self.Fx = fx
        self.Fy = fy
        self.dFy = dfy
    
    def get_value(self, x: float | int) -> float:
        index = self.Fx.index(int(x))

        if float(x).is_integer():
            return self.Fy[index]
        
        Ai = index
        Bi = index + 1

        Ax, Bx = self.Fx[Ai], self.Fx[Bi]
        Ay, By = self.Fy[Ai], self.Fy[Bi]
        dAy, dBy = self.dFy[Ai], self.dFy[Bi]

        if dAy == dBy:
            Vx = (Ax + Bx)/2
            Vy = (Ay + By)/2
        else:
            Vx = (By - Ay + dAy*Ax - dBy*Bx)/(dAy - dBy)
            Vy = Ay + dAy*(Vx - Ax)
        
        denominator = (Ax - Bx)**2
        p = (Ax - 2*Vx + Bx)/denominator
        if p != 0:
            q = 2*(Ax*Vx - 2*Ax*Bx + Vx*Bx)/denominator
            x = ((4*p*(x - Ax*Bx*p) + q*q)**0.5 - q)/(2*p)
        
        y = (Ay*((Bx - x)**2) + (Ax - x)*(Ax*By - 2*Vy*(Bx - x) - By*x))/((Ax - Bx)**2)

        return y

    def __call__(self, density: int):
        Ex, Ey = [], []
        for x in range(self.Fx[0]*density, self.Fx[-1]*density + 1):
            x /= density
            Ex.append(x)
            Ey.append(self.get_value(x))
        
        return (Ex, Ey)


if __name__ == "__main__":
    import matplotlib.pyplot as plt

    fx, fy, dfy = [-3, -2, -1, 0], [1, 1, 2, 6], [-0.577215664902, 0.422784335098, 1.8455686702, 7.53670601059]

    G = Expand(fx, fy, dfy)
    gx, gy = G(2)

    plt.plot(fx, fy, color="b")
    plt.plot(gx, gy, color="r")
    plt.show()

当初始函数

fx
的点的x值列表以正值开始时,代码似乎可以正常工作,但是如果我将这些值移动负数(在纸面上只会将输出值移动到左)如果偏移量很小,则所得的近似值在某些值附近会失真,否则会弹出索引错误。

这是错误消息:

Traceback (most recent call last):
  File "c:\Users\marco\Documents\My Programs\Personal\Expand.py", line 53, in <module>
    gx, gy = G(2)
             ^^^^
  File "c:\Users\marco\Documents\My Programs\Personal\Expand.py", line 42, in __call__
    Ey.append(self.get_value(x))
              ^^^^^^^^^^^^^^^^^
  File "c:\Users\marco\Documents\My Programs\Personal\Expand.py", line 16, in get_value
    Ax, Bx = self.Fx[Ai], self.Fx[Bi]
                          ~~~~~~~^^^^
IndexError: list index out of range

我检查了变量的值

Ax
,
Bx
,
Ay
,
By
,
dAy
,
dBy
,
Vx
,
Vx
,
denominator
,
p
,
 q
x
y
但这似乎不是问题,因为获取每个变量的公式都可以正确工作。

我认为错误必须来自

__call__
方法或我找到变量的方式
index

python indexoutofboundsexception
1个回答
0
投票

问题现在已解决,我只需导入数学模块并将

index = self.Fx.index(int(x))
替换为
index = self.Fx.index(math.floor(x))

事实证明,对于正值,函数 int(x) 的工作原理与 Floor(x) 类似,但对于负值则不然,例如:

int(2.5) = 2
楼层(2.5) = 2

int(-2.5) = -2
楼层(-2.5) = -3

© www.soinside.com 2019 - 2024. All rights reserved.