Search code examples
pythonmathquadraticequation-solving

Solving Quadratic Formula


I'm writing a program to solve quadratic equations using the quadratic formula but it only works when a = 1 but i want it to work when a is more than 1

Here is my code:

import math

def solve(a, b, c):

    x = ((-1)* b + math.sqrt(b**2-4*a*c))/2*a
    print "x = %s" %x
    print "or"
    y = ((-1)* b - math.sqrt(b**2-4*a*c))/2*a
    print "x = %s" %x




while 1:
    a = int(raw_input("Enter A :"))
    b = int(raw_input("Enter B :"))
    c = int(raw_input("Enter C :")) 
    solve(a, b, c)

It works with 1 but when I use a number more than one when i use say 4 i get this error

Traceback (most recent call last):
  File "C:\Documents and Settings\User\Desktop\Factor.py", line 18, in <module>
    solve(a, b, c)
  File "C:\Documents and Settings\User\Desktop\Factor.py", line 5, in solve
    x = ((-1)* b + math.sqrt(b**2-4*a*c))/2*a
ValueError: math domain error

is there a way around this if so help!!


Solution

  • The problems are here:

    1. operator precedence: your /2*a should be /(2*a) to work correctly.
    2. the domain of sqrt: math.sqrt bails on negative numbers.
    3. Edit 2: y = ... just after print "or" should be x = ...

    To fix the latter, you'll need some sort of conditional:

    disc = b**2 - 4*a*c
    sqrtdisc = math.sqrt(disc) if disc >= 0 else math.sqrt(-disc)*1j
    

    Edit: You could also use cmath.sqrt, which automatically handles negative numbers:

    disc = b**2 - 4*a*c
    sqrtdisc = cmath.sqrt(disc)
    

    (Thanks to various other answerers for effectively letting me know that cmath exists.)