0

I am trying to create a simple program to sole for the roots of a quadratic equation in python, but my code is not working. Here is what I have so far:

from math import *
def qf(a, b, c):
    print((-b+sqrt(b*b-4*a*c))/(2*a));
    print((-b-sqrt(b*b-4*a*c))/(2*a));
while(True):
    qf(input("A: "), input("B: "), input("C: "))

And here are the errors I get when evaluating:

Traceback (most recent call last):
  File "qf.py", line 6, in <module>
    qf(input("A: "), input("B: "), input("C: "))
  File "qf.py", line 3, in qf
    print((-b+sqrt(b*b-4*a*c))/(2*a));
ValueError: math domain error

What errors have I made, and how can I fix them?

Programah
  • 179
  • 1
  • 10

2 Answers2

2

Try this:

from math import *
def qf(a, b, c):
    if b*b < 4*a*c:
        print("cannot compute qf({}, {}, {})".format(a, b, c))
        return
    print((-b+sqrt(b*b-4*a*c))/(2*a));
    print((-b-sqrt(b*b-4*a*c))/(2*a));
while(True):
    qf(float(input("A: ")), float(input("B: ")), float(input("C: ")))

You need to make sure that you don't pass negative values to sqrt(). Additionally you should convert the result of input() to a numerical type.

Flurin
  • 681
  • 5
  • 14
0

This code allows you to enter the three values in a quadralic equasion and returns the roots or states that there are no roots:

import math
def solveQuadratic(a,b,c):
    dis = discriminant(a,b,c)
    if dis < 0:
        print('no real roots')
    else:
        sqdis = math.sqrt(dis)
        topOne = -b+sqdis
        B = 2*a
        firstRoot = topOne/B
        firstRoot = str(firstRoot)
        print ('the first root is: '+firstRoot)
        topTwo = -b-sqdis
        B = 2*a
        secondRoot = topTwo/B
        secondRoot = str(secondRoot)
        print ('the second root is: '+secondRoot)
def discriminant(a,b,c):
    fp = b*b
    ac = a*c
    sp = -4*ac
    dis = fp+sp
    return (dis)

print('enter first coefficient')
a = input()
a = int(a)
print('enter second coefficient')
b = input()
b = int(b)
print('enter the constant')
c = input()
c = int(c)
solveQuadratic(a,b,c)