Home > Back-end >  I wrote quadratic equations program in python but one solution is being calculated wrong when 2nd on
I wrote quadratic equations program in python but one solution is being calculated wrong when 2nd on

Time:11-14

I am trying to solve quadratic equations using Python, my program finds solutions but first one is being calculated wrong, I checked the code several times and can't find what am I doing wrong

a = 2  # random.randint(1, 10)
b = 9  # random.randint(-110, 10000)
c = 4  # random.randint(-10000, 10000000)

d = (b ** 2)   (- 4 * a * c)
print(d)

if d < 0:
    print('x does not exist')
elif d == 0:
    print((-1 * b) / 2 * a)
else:
    print('x exists')


def sqrt(n):
    if n < 0:
        return
    else:
        return n ** 0.5


x_1 = (-1 * b - sqrt(b)) / 4
x_2 = (-1 * b   sqrt(b)) / 4

print(f'solution 1 is: {round(x_1)}, solution 2 is: {round(x_2)}')

CodePudding user response:

In the formula:

x_1 = (-1 * b - sqrt(b)) / 4

sqrt(b) should be sqrt(d).

Also in the print statement:

print(f'solution 1 is: {round(x_1)}, solution 2 is: {round(x_2)}')

The round function is confusing.

You could change it to:

print(f'solution 1 is: {(x_1)}, solution 2 is: {(x_2)}')

CodePudding user response:

Your x1 and x2 expressions are not correct. It should be: x_1=(-1*b sqrt(d))/(2*a)

x_2=(-1*b-sqrt(d))/(2*a)

  • Related