在Python中分解二次多项式
因为我脑子里能很快地把二次方程拆解开来,这种能力从我学会它的时候就有了。那么我该如何开始用Python写一个能拆解二次方程的程序呢?
3 个回答
2
我试着按照hugomg的方法来做。我从网上抄了“gcd”(最大公约数)和“简化分数”的函数。下面是我这个不太严谨的方法:
from math import sqrt
def gcd(a, b):
while b:
a, b = b, a % b
return a
def simplify_fraction(numer, denom):
if denom == 0:
return "Division by 0 - result undefined"
# Remove greatest common divisor:
common_divisor = gcd(numer, denom)
(reduced_num, reduced_den) = (numer / common_divisor, denom / common_divisor)
# Note that reduced_den > 0 as documented in the gcd function.
if common_divisor == 1:
return (numer, denom)
else:
# Bunch of nonsense to make sure denominator is negative if possible
if (reduced_den > denom):
if (reduced_den * reduced_num < 0):
return(-reduced_num, -reduced_den)
else:
return (reduced_num, reduced_den)
else:
return (reduced_num, reduced_den)
def quadratic_function(a,b,c):
if (b**2-4*a*c >= 0):
x1 = (-b+sqrt(b**2-4*a*c))/(2*a)
x2 = (-b-sqrt(b**2-4*a*c))/(2*a)
# Added a "-" to these next 2 values because they would be moved to the other side of the equation
mult1 = -x1 * a
mult2 = -x2 * a
(num1,den1) = simplify_fraction(a,mult1)
(num2,den2) = simplify_fraction(a,mult2)
if ((num1 > a) or (num2 > a)):
# simplify fraction will make too large of num and denom to try to make a sqrt work
print("No factorization")
else:
# Getting ready to make the print look nice
if (den1 > 0):
sign1 = "+"
else:
sign1 = ""
if (den2 > 0):
sign2 = "+"
else:
sign2 = ""
print("({}x{}{})({}x{}{})".format(int(num1),sign1,int(den1),int(num2),sign2,int(den2)))
else:
# if the part under the sqrt is negative, you have a solution with i
print("Solutions are imaginary")
return
# This function takes in a, b, and c from the equation:
# ax^2 + bx + c
# and prints out the factorization if there is one
quadratic_function(7,27,-4)
如果我运行这个代码,我得到的输出是:
(7x-1)(1x+4)
6
使用二次公式。
6
改进Keith的回答:
首先,从一个多项式开始,形如 P(x) = a*x^2 + b*x + c
。
接下来,使用二次公式(或者你喜欢的其他方法)来找到方程 P(x) = 0
的根,也就是 r1
和 r2
。
现在你可以把这个多项式分解成 a*(x-r1)(x-r2)
的形式。
如果你的因式是 (3x - 4)(x - 9),那么解会是 3*(x - 4/3)(x - 9)。
你可能想找个方法把3乘到因式里,这样就可以去掉分数,让结果看起来更整齐。在这种情况下,使用分数运算而不是浮点数运算可能会更好,这样你能更清楚地知道分母是什么。