Python數學實現二元一次方程


 1 import cmath
 2 import  math
 3 import  sys
 4 
 5 def get_float(msg,allow_zero):
 6     x = None
 7     while x is None:
 8         try:
 9             x = float(input(msg))
10             if not allow_zero and abs(x) <sys.float_info.epsilon:
11                 print("zero is not allowed")
12                 x = None
13         except ValueError as err:
14             print(err)
15     return x
16 
17 print("ax\N{SUPERSCRIPT TWO} +bx +c = 0")
18 a = get_float("enter a:", False)
19 b = get_float("enter b:", True)
20 c = get_float("enter c:", True)
21 x1 = None
22 x2 = None
23 discriminant = (b**2)-(4*a*c)
24 if discriminant == 0:
25     x1 = -(b/(2*a))
26 else:
27     if discriminant >0:
28         root  = math.sqrt(discriminant)
29     else:
30         root = cmath.sqrt(discriminant)
31 
32     x1 = (-b+root) / (2*a)
33     x2 = (-b -root) /(2*a)
34 
35 equation = ("{0}x\N{SUPERSCRIPT TWO}+{1}+{2} = 0""\N{RIGHTWARDS ARROW}X = {3}").format(a,b,c,x1)
36 if x2 is not None:
37     equation += "  or x = {0}".format(x2)
38 print(equation)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM