solveQuadratic Function

private function solveQuadratic(a, b, c, x0, x1)

solves quadratic equation given coeffs a, b, and c returns true if real solution returns x0 and x1 adapted from scratchapixel

Arguments

Type IntentOptional Attributes Name
real(kind=wp), intent(in) :: a
real(kind=wp), intent(in) :: b
real(kind=wp), intent(in) :: c
real(kind=wp), intent(out) :: x0
real(kind=wp), intent(out) :: x1

Return Value logical


Source Code

    logical function solveQuadratic(a, b, c, x0, x1)
    !! solves quadratic equation given coeffs a, b, and c
    !! returns true if real solution
    !! returns x0 and x1
    !! adapted from scratchapixel

        real(kind=wp), intent(IN)  :: a, b, c
        real(kind=wp), intent(OUT) :: x0, x1

        real(kind=wp) :: discrim, q

        solveQuadratic = .false.

        discrim = b**2 - 4._wp * a * c
        if(discrim < 0._wp)then
            return
        elseif(discrim == 0._wp)then
            x0 = -0.5_wp*b/a
            x1 = x0
        else
            if(b > 0._wp)then
                q = -0.5_wp * (b + sqrt(discrim))
            else
                q = -0.5_wp * (b - sqrt(discrim))
            end if
            x0 = q / a
            x1 = c / q
        end if
        solveQuadratic = .true.
        return

    end function solveQuadratic