How to Find the Roots of a Quadratic Equation

Fomula for Roots of a Quadratic Equation
Solving a quadratic equation for real and complex solutions is at the core of mathematics. Let us see how carry out this process in Fortran.


  • We will have two read the quadratic coefficients a,b,c  for the program. They define the equation ax**2+b*x+c=0.
  • Once we do this, we calculate discriminant to know whether the roots are real and complex as shown in the figure.
  • Note that when D<0, we cannot calculate its square root. Therefore, we use the formula for complex roots (which is pretty much the same except that you get a non-zero imaginary part).
  • Additionally, we can calculate the modulus of the roots.i.e. how far they are from the origin of the complex plane, using modulus r=sqrt (x**2+y**2), where x and y are the real and imaginary parts of the roots.
  • For real roots, we can easily calculate the second root, if we know the first. We know that the sum of the roots is (-b/a) and the product of the roots is c/a. We can display these values as well.
Now for the Fortran program,

 !To find the roots of a quadratic equation
program quadratic
    implicit none
    real a,b,c,d,p,rootd,x1,x2,realroot,imagroot
  
    write(*,*) "Give a,b,c"
    read (*,*) a,b,c
    write(*,*) "a= ",a,"b= ",b,"c= ",c
  
    d=(b*b)-(4*a*c)
    write (*,*) "The discriminant is", d
  
    write (*,*) "Finding the solutions to the quadratic equation:"
    write (*,*) "(",a,")x^2+ (",b,")x + (",c,")"
  
    !For complex roots
    If (d<0) then
          rootd=sqrt(-d)
          write (*,*) "The discriminant is less than zero. Roots are complex"
          x1=(-b)/(2*a) + (-rootd)/(2*a)
          x2=(-b)/(2*a) - (-rootd)/(2*a)
          realroot=(x1+x2)/2
          imagroot=(x1-x2)/2
        write (*,*) "Root1= ",realroot," + ",imagroot,"i"
        write (*,*) "Root2= ",realroot," - ",imagroot,"i"
        write(*,*) "Real part of root= ", abs(realroot)," Imaginary part of root= ", abs(imagroot)
        write (*,*) "The modulus is", sqrt(realroot**2+imagroot**2)
          else
        
        !For real roots
          p=(-b)
        rootd=sqrt(d)
        write (*,*) "The discriminant is greater than or equal to zero. The roots are real."
          if (p>0) then
            x1=(-b)/(2*a)+rootd/(2*a)
            else
            x1=(-b)/(2*a)-rootd/(2*a)
          end if
          x2=c/(a*x1)
      
          write(*,*) "Root1= ",x1,"Root2= ",x2
        write (*,*) "The sum of the roots is ",x1+x2," and (-b/a) is ",-b/a
           write (*,*) "The product of the roots is ",x1*x2," and (c/a) is ",c/a
    end if
 end program quadratic


Sample Output for D>0

Sample Output for D=0

Sample Output for D>0

3 comments:

  1. https://smartlearning020.blogspot.com/2021/02/complex-roots-of-quadratic-equations-in.html

    ReplyDelete
  2. https://smartlearning020.blogspot.com/

    ReplyDelete