#!/bin/bash
## solve a quadratic equation of a * x^2 + b * x + c = 0.
## date: Feb. 01, 2016.
## author: Xiaoxu Guan at LSU HPC.


NOARG=3

if [[ $# -ne NOARG ]] ; then
      echo "usage: three arguments for a, b, and c are required for a * x^2 +b * x +c = 0." 
      echo "exit 10"
      exit 10
fi

a=$1
b=$2
c=$3

a2=$((a+a))
temp=$((b*b-4*a*c))


echo "solutions to " $1 "*x^2 + "$2 "*x " "+ "$3 "= 0"

if [[ temp -lt 0 ]] ; then
# complex solutions:
      echo "two complex solutions:"
      let temp=-temp 
      st=`echo "scale=5 ; sqrt($temp)"  |  bc`
      x1_r=`echo "scale=5 ; (-1)*$b/$a2"  |  bc`
      x1_i=`echo "scale=5 ; $st/$a2"  |  bc`
      x2_r=$x1_r
      x2_i=`echo "scale=5 ; (-1)*$st/$a2"  |  bc`
      echo "x1 = "  $x1_r " + i " $x1_i
      echo "x2 = "  $x2_r " + i " $x2_i
elif [[ temp -eq 0 ]] ; then
# one real solution:
      echo "only one real solution:"
      x=`echo "scale=5 ; (-1)*$b/$a2"  | bc`
      echo "x = " $x
else
# two real solutions:
      echo "two real solutions:"
      st=`echo "scale=5 ; sqrt($temp)"  |  bc`
      x1=`echo "scale=5 ; ($st-$b)/$a2" | bc`
      x2=`echo "scale=5 ; (-$st-$b)/$a2 " | bc`
      echo "x1 = " $x1
      echo "x2 = " $x2
fi
