113k views
1 vote
Write a MATLAB program to solve for the roots of a quadratic equations, regardless of type. Use complex variables so that no branches will be required based on the value of the discriminant. g

User YOLO
by
7.3k points

1 Answer

3 votes

Step-by-step explanation:

PROGRAM QuadraticEquation

IMPLICIT NONE

REAL :: a, b, c

REAL :: d

REAL :: root1, root2

! read in the coefficients a, b and c

READ(*,*) a, b, c

WRITE(*,*) 'a = ', a

WRITE(*,*) 'b = ', b

WRITE(*,*) 'c = ', c

WRITE(*,*)

! compute the square root of discriminant d

d = b*b - 4.0*a*c

IF (d >= 0.0) THEN

d = SQRT(d)

root1 = (-b + d)/(2.0*a)

root2 = (-b - d)/(2.0*a)

WRITE(*,*) 'Roots are ', root1, ' and ', root2

ELSE

WRITE(*,*) 'no real roots exist!'

WRITE(*,*) 'Discriminant = ', d

END IF

END PROGRAM QuadraticEquation

User MikePatel
by
7.3k points