Quadratic Equation Solver Using TCL

Basic Quadratic Equation Format: ax^2 + bx + c = 0, where a ≠ 0

Formula: 


The (b^2 - 4ac) part is called the discriminant and based on the value of the discriminant there can be 3 possible solutions:
  • when it is positive, there are two real solutions,
  • when it is zero, there is just one solution,
  • when it is negative, there are complex solutions.

Code:

#!/mingw64/bin/tclsh

set eqn "5x^2+x-1=0"
set segs [split $eqn "+|-|=0"]
# puts $segs
set degree {}
set co_eff {}
set co_si {}

#find the degree
foreach seg $segs { 
	if {[regexp {x\^(\d+)} $seg -- power ]} {
		lappend degree $power
	} elseif {[regexp {x} $seg -- power ]} {
		lappend degree 1
	}
}

if {[lindex $degree 0] == 2} {
	puts "$eqn is a second order equation"
} else {
	puts "Please! Put a second order equation! Please.."
}

# get the co-efficients
foreach seg $segs { 
	if {$seg != ""} {
		if {[regexp {(\d+)x} $seg -- coeff ]} {
			lappend co_eff $coeff
		} elseif {[regexp {(x\^\d)} $seg -- coeff ]} {
			lappend co_eff 1
		} elseif {[regexp {(x)} $seg -- coeff ]} {
			lappend co_eff 1
		} elseif {[regexp {(\d+)} $seg -- coeff ]} {
			lappend co_eff $coeff
		} else {
			lappend co_eff 0
		}
	}
}

set signs [regexp -all -inline {\+|\-} $eqn]

if { [ llength $co_eff] == [ llength $signs]} {
	set signs $signs	 
} else {
	set signs [ linsert $signs 0 +]
}

for {set i 0} {$i < [llength $signs]} {incr i} {
	set co "[lindex $signs $i][lindex $co_eff $i]"
	lappend co_si $co
}

puts "Co-efficients: $co_si"

set a [lindex $co_si 0]
set b [lindex $co_si 1]
set c [lindex $co_si 2]

set discriminant [expr ($b ** 2) - (4 * $a * $c)]
puts "Value of discriminant: $discriminant"
if {$discriminant > 0} {
	puts "The equation has 2 real solutions"
	set x1 [expr (-$b + sqrt($discriminant))/ (2* $a)]
	set x2 [expr (-$b - sqrt($discriminant))/ (2* $a)]
	puts "The roots of $eqn are: $x1 and $x2"
} elseif {$discriminant == 0} {
	puts "The equation has 1 real solution"
	set x1 [expr -$b / (2* $a)]
	puts "The roots of $eqn are: $x1"
} else {
	puts "The equation has complex solutions"
}

Result:

5x^2+x-1=0 is a second order equation
Co-efficients: +5 +1 -1
Value of discriminant: 21
The equation has 2 real solutions
The roots of 5x^2+x-1=0 are: 0.35825756949558396 and -0.558257569495584

Future Improvements:

  • Now this script can only solve quadratic equations with the format ax^2 + bx + c = 0. The script can be adapted to solve any formatted equations like, bx + ax^2 = -c

Post a Comment

0 Comments