Skip to main content
 首页 » 编程设计

python之求解二次和三次多项式的三次函数

2025年05月04日9JustinYoung

我有一个正在编写的程序,用户可以在其中选择求解二次或三次多项式的三次函数。选择后,程序会应用多个公式,包括:求解二次判别式、二次方程式、二次多项式的公式、Cardano 的三次多项式类似方法和标准三次方程式(基本上,第一个page 上的四个公式)。

这是我的代码:

import math 
 
def deg3(): 
    print("This is a third degree polynomial calculator.") 
    print("Please enter four numbers.") 
    a = int(input()) 
    b = int(input()) 
    c = int(input()) 
    d = int(input()) 
 
# Apply Cardano's compressed method to find x root, broken up into different variables. 
p = (-1 * b)/(3 * a) 
q = p ** 3 + (b * c - (3 * a * d))/ (6 * (a ** 2))  
r = c / (3 * a) 
 
x = (q + (q**2 + (r - p**2)**3) **1/2) **1/3 + (q + (q**2 + (r - p**2)**3) **1/2) **1/3 + p 
print("The root is:", x) 
 
# Applies final cubic formula, and returns. 
total = (a * x**3) + (b * x**2) + (c * x) + d 
total = round(total, 3) 
return total 
 
# If discr > 0, then the equation has three distinct real roots. 
# If discr = 0, then the equation has a multiple root and all its roots are real. 
# If discr < 0, then the equation has one real root and 
# two nonreal complex conjugate roots. 

现在它很容易返回总数。计算是正确的,但我仍在努力思考类似的公式。方程的判别部分是什么?我如何找到潜在的根,就像我使用二次公式一样?可能是一个简单的问题,但我想更好地理解这个过程。

请您参考如下方法:

首先,您的三次函数与您链接到的站点上的方程之间存在许多差异。其中最著名的是:

  1. 你的操作顺序是错误的:像这样的一行:

    big = (-1 *( b**3 / 27 * a**3) + (b * c / 6 * a**2) - (d / 2 * a)) 
    

    应该是:

    big = (-1 *( b**3 / (27 * a**3)) + (b * c / (6 * a**2)) - (d / (2 * a))) 
    

    否则,像 27 * a**3 这样的项将不会出现在分母中 - 它会在分母中被视为 27 而 a**3 之后。

  2. 您永远不会包含立方根,即使您链接到的方程式中有两个。

  3. 您做 x * 2 - small,但是等式中加在一起的两项并不相同 - 一个有一个加号,另一个有一个负号。

但是,即使您解决了函数的所有问题,在尝试求解许多三次方程时仍然会出现数学域错误。请注意您链接中的这一段:

But if we apply Cardano's formula to this example, we use a=1, b=0, c=-15, d=-4, and we find that we need to take the square root of -109 in the resulting computation. Ultimately, the square roots of negative numbers would cancel out later in the computation, but that computation can't be understood by a calculus student without additional discussion of complex numbers.

求解三次方程需要处理复数(尽管只是暂时的——如前所述,它们会相互抵消),因此您不能使用 math.sqrt 来求解。您可能对 cmath 感兴趣包。