由於在我的腦海中考慮二次方程剛剛發生,並且自從我學會了這一步以來就做了 - 我該如何開始在Python中編寫二次因式分解器?在Python中分解二次多項式
1
A
回答
5
提高Keiths的回答是:
開始用多項式P(x) = a*x^2 + b*x + c
。 使用二次公式(或您選擇的其他方法)找到根r1
和r2
至P(x) = 0
。
您現在可以將P(x)分解爲a*(x-r1)(x-r2)
。如果你的因子(3x-4)(x-9)的解答是3 *(x-4/3)(x-9),那麼這個解決方案將會是3 *(x-4)。 您可能想要找到一種方法將3乘以因子以擺脫分數/看起來很漂亮。在這種情況下,它可能有助於使用分數算術而不是雙打,因此您可以更好地瞭解分母。
6
0
我試着實施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)
相關問題
- 1. Python的二次多項式的根
- 2. 基本斯卡拉 - 二次多項式
- 3. 二次多項式和strightline的分段迴歸
- 4. 解二次方程式
- 5. Python中的多項式的劃分
- 6. 的Python:創建n次多項式
- 7. 在C中求解多項式(4,二階)的系統
- 8. 如何求解二階和二階微分方程(在python中)?
- 9. Python PLY零次或多次出現的解析項目
- 10. 在Python中求解困難(多項式?)方程
- 11. 在Python中使用MATLAB函數求解四階多項式
- 12. 改性負二項式GLM在Python
- 13. Python中的Beta二項式函數
- 14. 解析多層次的Json在python
- 15. 在Python中求解等於0的二次方程
- 16. 二次公式解決方案問題
- 17. 在二次迴歸中使用奇異值分解(svd)
- 18. Python二次公式不起作用
- 19. 在序言中解決二次方程
- 20. 給定三元組生成二次多項式
- 21. 從3元組生成二次多項式
- 22. 解決二項函數的Python函數
- 23. 如何在Matlab中用'n'個變量(二次多項式)求解'n'(非線性)方程組?
- 24. Python中模式的多次發生
- 25. 用於分解多項式表達式的正則表達式
- 26. 二項分佈式輸出使用Python的CDF/PMF
- 27. 如何求解python中的多項式特徵值?
- 28. 使用python解析二進制格式
- 29. 在Python中解釋二進制數據
- 30. 在Python中一次更改列表中的多個項目
到的因素呢?沒有解決 – tekknolagi 2011-02-15 01:05:22
他們基本上是等效的。查看引用頁面的Quadratic Factorization部分。 – 2011-02-15 01:06:50