What codes do i need for fortran quadratic program to enable it evaluate the LHS of the equation.(x=root1)?

! This program finds the roots of equations of the 2nd degree

! with coefficients a, b and c

program Equation

implicit none

real*4 a, b, c, delta

real*4 root1, root2

integer*1 count

! ----------------------------------------------Prompt and Input

print*, "Solves ax^2 + bx + c = 0"

print*, "Enter the coefficients a,b,c separated by commas..."

read*, a, b, c

! ----------------------------------------------Validate

! ----------------------------------------------Find delta

delta = b**2 - 4.* a * c

! ----------------------------------------------Determine Roots

if (delta .GT. 0.) then

root1 = (-b + sqrt(delta)) / (2. * a)

root2 = (-b - sqrt(delta)) / (2. * a)

count = 2

else if (delta .LT. 0.) then

count = 0


root1 = -b / (2. * a)

count = 1

end if

! ----------------------------------------------Show Results

if (count .EQ. 2) then

write(*,20) " Equation has two roots: ", root1, ", ", root2

else if (count .EQ. 1) then

write(*,20) " Equation has one root: ", root1


write(*,20) " Equation has no real roots!"

end if

20 format(1x, A, F10.4, A, F10.4)

! ----------------------------------------------Verify root1

if (count .GT. 0) then

print*, "Verifying the first root by computing the L.H.S.:"

end if

! ----------------------------------------------


2 Answers

  • 10 years ago
    Favorite Answer

    I am surprised at Scott H otherwise valid answer that he used the long (and less efficient) form (programming teachers used to scold people for doing it that way).

    The way to compute it is:

    LHS=(a*root1+b)*root1 + c

    that is 4 floating point operations against the 5 of the brute force approach. The impact is more significant for higher degree polynomials.

    And to reduce the operation count even more,


    and then validate cc against c, i.e.

    IF(cc.EQ.c) write(*,30) "Root validated"

    30 FORMAT(A)

  • 10 years ago

    verify = a*root1*root1 + b*root1 + c

    IF (verify .EQ. 0.0) THEN PRINT *, 'Quadratic equation validated for ', root1

    UPDATE: You're right Vincent G -- I was too lazy to write out the quicker form. But, I did show the use of multiplication versus exponentiation ;)

Still have questions? Get your answers by asking now.