Check if delta is less than zero (Bhaskara’s formula)

Asked

Viewed 265 times

-1

Basically what I need is if delta is greater than 0 should stop and show a message of "There is no root", but I’m not able to put the: D < 0 print('Não existe raízes'). Can someone help me?

Follows the code:

def raizes(a, b, c):
    D = (b**2 - 4*a*c)
    x1 = (-b + D**(1/2)) / (2*a)
    x2 = (-b - D**(1/2)) / (2*a)

    print('\nValor de x1: {0}'.format(x1))
    print('Valor de x2: {0}'.format(x2))

if __name__ == '__main__':
    while True:
        print('Calculando as raízes de uma equação de 2º grau\n')
        a = float(input('Entre com o valor de a: '))
        b = float(input('Entre com o valor de b: '))
        c = float(input('Entre com o valor de c: '))
        raizes(a,b,c)
        
                
        continua = input('Deseja sair? Digite q ou Enter para novo cálculo:')
        if (continua == 'q'):
            break
  • Please format the code. And put what you have tried.

  • Try: if D < 0: print('Não existe raízes') else: ...

  • That message from continua = input(...) confused. Hints that typing 'q' or 'Enter' the program will continue running

4 answers

2

To resolve this issue you should pay attention to some things, such as:

  1. Knowing how to capture the values of coefficients;
  2. Calculate the value of delta and, also, the roots;
  3. Correctly display function return - according to your constraints;
  4. Implement a noose to re-enter the code, if the user wishes.

Putting this logic into practice, I implemented the following code:

def raizes(a, b, c):
    d = ((b ** 2) - (4 * a * c))
    if d < 0:
        msg = 'Não existe raízes Reais!'
        return msg
    else:
        x1 = round(((-b + (d ** (1 / 2))) / (2 * a)), 1)
        x2 = round(((-b - (d ** (1 / 2))) / (2 * a)), 1)

        if x1 == -0.0:
            x1 = 0
        if x2 == -0.0:
            x2 = 0

        menor = x1
        if x2 < x1:
            maior = x1
            menor = x2
        else:
            maior = x2

        if d == 0:
            msg = f'Duas raízes Reais iguais: x1 = {menor} e x2 = {maior}'
            return msg
        else:
            msg = f'Duas raízes Reais diferentes: x1 = {menor} e x2 = {maior}'
            return msg


while True:
    coef_A, coef_B, coef_C = list(map(float, input('Coeficientes "A", "B" e "C": ').split()))

    print(raizes(coef_A, coef_B, coef_C))

    resp = input('Desejas realizar novo cálculo? [S/N]: ').upper()
    while (len(resp) != 1) or (resp not in 'SN'):
        print('Valor INVÁLIDO! Digite apenas "S" ou "N"!')
        resp = input('Desejas realizar novo cálculo? [S/N]: ').upper()
    if resp == 'N':
        break

Note that when we execute this code we receive the following message: Coeficientes "A", "B" e "C": . At this point we must enter the 3 coefficients of that equation, in same line, separated for a single space and press enter. At this time the entered values are captured and sent as parameters to the function roots(a, b, c). Arriving there will be calculated the delta value - d. Once the result of the delta is reached, it shall be verified whether this value is less than 0. If this value is in fact less than 0 the return of the function will be: "Não existe raízes reais". If this value is different from 0 the code flow will be diverted to the block Else.

Once there, the roots of the quadratic function will be calculated.

OBSERVING:

According to the Fundamental Theorem of Algebra,"Every nonconstant polynomial of degree n has n complex roots, not necessarily all distinct ones".

In short: any quadratic function will always have 2 roots, may be: 2 equal REAL roots or 2 different REAL roots or 2 different IMAGINARY roots

Well, at this point it will be checked whether the delta value - d - is equal to 0, or rather, if d == 0. If so, the quadratic function will have two equal real roots, i.e. X1 == x2. Otherwise, the quadratic function will have two different real roots, i.e., X1 != x2

After you have displayed the result of the calculations we receive the following message: Desejas realizar novo cálculo? [S/N]: . Right now we must type S, to perform recalculation or N to end the execution of the code.

Let’s test the code?

Example 1:

Calculate the roots of the quadratic function x² - 3x + 2.

At this time we execute the code and when we receive the message: Coeficientes "A", "B" e "C": . We should type...

1 -3 2

...and press enter.

At this point the code will perform the calculations and provide us with the following output:

Duas raízes Reais diferentes: x1 = 1.0 e x2 = 2.0
Desejas realizar novo cálculo? [S/N]: 

If we want to perform a new calculation just press the letter S. Otherwise, we should press the letter N.

Example 2

Calculate the roots of the quadratic function -3x² + 6.

Observing: In this role we do not have the coefficient of B. In this case we will type 0 for the value of the coefficient of "B".

Then we execute the code and when we receive the message: Coeficientes "A", "B" e "C": . We should type...

-3 0 6

...and press enter. At this point the code will perform the calculations and provide us with the following output:

Duas raízes Reais diferentes: x1 = -1.4 e x2 = 1.4
Desejas realizar novo cálculo? [S/N]: 

Example 3

Calculate the roots of the quadratic function x - 2x².

Observing: In this function we have the order of the terms exchanged. In this question the A == -2, the B == 1 and C == 0.

Then we execute the code and when we receive the message: Coeficientes "A", "B" e "C": . We should type...

-2 1 0

...and press enter. At this point the code will perform the calculations and provide us with the following output:

Duas raízes Reais diferentes: x1 = 0 e x2 = 0.5
Desejas realizar novo cálculo? [S/N]: 

Example 4

Calculate the real roots of the quadratic function x² + 4x + 5.

Then we execute the code and when we receive the message: Coeficientes "A", "B" e "C": . We should type...

1 4 5

...and press enter. At this point the code will perform the calculations and provide us with the following output:

Não existe raízes Reais!
Desejas realizar novo cálculo? [S/N]: 

Example 5

Calculate the real roots of the quadratic function x² + 4x + 4.

Then we execute the code and when we receive the message: Coeficientes "A", "B" e "C": . We should type...

1 4 4

...and press enter. At this point the code will perform the calculations and provide us with the following output:

Duas raízes Reais iguais: x1 = -2.0 e x2 = -2.0
Desejas realizar novo cálculo? [S/N]: 

0

Just use if/else:

from math import sqrt

def raizes(a, b, c):
    delta = b ** 2 - 4 * a * c
    if delta < 0:
        print('Não existem raízes reais')
    else:
        dois_a = 2 * a
        if delta == 0:
            print(f'Raiz: {-b / dois_a }')
        else:
            raiz_delta = sqrt(delta)
            x1 = -b + raiz_delta / dois_a
            x2 = -b - raiz_delta / dois_a
            print(f'Valor de x1: {x1}')
            print(f'Valor de x2: {x2}')

I’ve changed some things too.

If the delta is zero, there is only one root (technically, they are "2 equal roots", but anyway), and in this case you do not need to calculate the square root (because the square root of zero is zero) and not calculate 2 roots (the 2 accounts will give the same result). So in this case you can print only one root.

Only if the delta is greater than zero, then I calculate the root, and do it only once, keeping the result in a variable - funny that people often create variables without need, but in this case there is gain (because I only need to calculate the root once), many prefer to redo the calculation instead of doing it once and save it in a variable (of course the difference in performance will be inconspicuous, it was just an observation).

0

I would explain that it has no real roots as there may be imaginary roots:

def raizes(a, b, c):
    D = (b**2 - 4*a*c)
    if D < 0:
        print('Não existem raízes reais')
    else:
         x1 = (-b + math.sqrt(D)) / (2*a)
         x2 = (-b - math.sqrt(D)) / (2*a)
         print('\nValor de x1: {0}'.format(x1))
         print('Valor de x2: {0}'.format(x2))

0

If you need to make a comparison with the delta value before showing the roots or not, separate the delta calculation from the root calculation.

delta  = lambda a, b, c: b**2 - 4*a*c
bhaskara = lambda a, b, delta: (
                                (-b + delta**(1/2)) / (2*a), 
                                (-b - delta**(1/2)) / (2*a)   )

def prompt(frase):  
    try: return float(input(frase))
    except: return prompt(frase)

frases = [f'Entre com o valor de {e}:' for e in ['a','b','c'] ]
continua = ''

if __name__ == '__main__':
    while continua != 'q':
        print('Calculando as raízes de uma equação de 2º grau\n')
        cf = [prompt(f) for f in frases] 
        d = delta(cf[0], cf[1], cf[2])        
        if d < 0:
           print('Não existem raízes reais.')
        else:          
          print("\n".join(
            [ f'Valor de x{e[0] + 1}: {e[1]}' for e in enumerate(bhaskara(cf[0], cf[1], d))]
          ))
        continua = input('\nPressione <Enter> para continuar ou "p" para sair.').lower()

Upshot:

Calculando as raízes de uma equação de 2º grau

Entre com o valor de a:1
Entre com o valor de b:0
Entre com o valor de c:-1
Valor de x1: 1.0
Valor de x2: -1.0

Pressione <Enter> para continuar ou "p" para sair.

Test the example on repl it.

Additional reading:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.