Python中的三次方程

2024-07-07 06:58:06 发布

您现在位置:Python中文网/ 问答频道 /正文

使用https://engineersfield.com/cubic-equation-formula/中的公式:

class CubicEquation():
    def __init__(self,a,b,c,d):
        '''initialize constants and formula'''
        q = (3*c - b**2) / 9
        r = -27*d + b*(9*c - 2*b**2)
        discriminant = q**3 + r**2
        s = r + sqrt(discriminant)
        t = r - sqrt(discriminant)
        term1 = sqrt(3 * ((-t + s) / 2))
        r13 = 2 * sqrt(q)

        self.cubic_equation = [\
            '-term1 + r13*cos(q**3 / 3)',\
            '-term1 + r13*cos(q**3 + (2 * pi)/3)',\
            '-term1 + r13*cos(q**3 + (4 * pi)/3)'\
            ]
    def solve(self):
        *--snip--*

然后用answer = eval(self.cubic_equation[index])调用它

使用args(1,1,1,1)调用此公式时,我收到了以下解决方案: -6.803217085397121, -8.226355957420402, -8.208435953185608 是的,我已经把我的公式和网站上的公式核对了三遍。你知道吗

这个函数的正确代码是什么?我当前的程序出了什么问题?你知道吗


Tags: term1httpsselfcomdefpisqrtcos