Advertisement
includelow

solve_quadratic_equation

Feb 18th, 2017
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. #! usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. import sys
  5. import math
  6. import cmath
  7.  
  8. def solve(_coefficients):
  9.     x = [None, None, None]
  10.     if (_coefficients[0] == 0) and (_coefficients[1] == 0):
  11.         if _coefficients[2] == 0:
  12.             x[2] = 3
  13.             return x
  14.     d = _coefficients[1] ** 2 - 4 * _coefficients[0] * _coefficients[2]
  15.     if d > 0:
  16.         d = math.sqrt(d)
  17.         x[0] = -(_coefficients[1] - d) / (2 * _coefficients[0])
  18.         x[1] = -(_coefficients[1] + d) / (2 * _coefficients[0])
  19.         x[2] = 2
  20.     elif d == 0:
  21.         x[0] = -(_coefficients[1]) / (2 * _coefficients[0])
  22.         x[2] = 1
  23.     else:
  24.         d = cmath.sqrt(d)
  25.         x[0] = -(_coefficients[1] - d) / (2 * _coefficients[0])
  26.         x[1] = -(_coefficients[1] + d) / (2 * _coefficients[0])
  27.         x[2] = 2
  28.     return x
  29.  
  30. if len(sys.argv) > 4:
  31.     print "Слишком много аргументов"
  32. elif len(sys.argv) < 4:
  33.     print "Слишком мало аргументов"
  34. else:
  35.     coeffs=sys.argv[1:]
  36.     try:
  37.         coeffs[0] = float(sys.argv[1])
  38.         coeffs[1] = float(sys.argv[2])
  39.         coeffs[2] = float(sys.argv[3])
  40.     except ValueError:
  41.         print "Один или несколько из введенных аргументов не являются числами"
  42.     else:
  43.         print "Квадратное уравнение : {0}*x^2+{1}*x+{2}=0".format(coeffs[0], coeffs[1], coeffs[2])
  44.         solution = solve(coeffs)
  45.         if solution[2] == 2:
  46.             print "Решение 1: {0}".format(solution[0])
  47.             print "Решение 2: {0}".format(solution[1])
  48.         elif solution[2] == 1:
  49.             print "Решение : {0}".format(solution[0])
  50.         elif solution[2] == 3:
  51.             print "Решение уравнения может быть любое число"
  52.         else:
  53.             print ("Решений нет")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement