#!/bin/bash # Equation solver in Bash solve_equation() { local a=$1 local b=$2 local c=$3 echo "Solving: ${a}x² + ${b}x + ${c} = 0" # Check if bc is available for floating point math if ! command -v bc &> /dev/null; then echo "Error: bc calculator is required but not installed. Install with: sudo apt install bc" return 1 fi # Linear equation (a = 0) if [ "$(echo "$a == 0" | bc -l)" -eq 1 ]; then if [ "$(echo "$b == 0" | bc -l)" -eq 1 ]; then if [ "$(echo "$c == 0" | bc -l)" -eq 1 ]; then echo "Infinite solutions" else echo "No solution" fi else local x=$(echo "scale=4; -($c) / $b" | bc) echo "Linear equation: x = $x" fi return fi # Quadratic equation local discriminant=$(echo "scale=4; $b*$b - 4*$a*$c" | bc) echo "Discriminant = $discriminant" if [ "$(echo "$discriminant > 0" | bc -l)" -eq 1 ]; then local x1=$(echo "scale=4; (-$b + sqrt($discriminant)) / (2*$a)" | bc) local x2=$(echo "scale=4; (-$b - sqrt($discriminant)) / (2*$a)" | bc) echo "Two real roots: x₁ = $x1, x₂ = $x2" elif [ "$(echo "$discriminant == 0" | bc -l)" -eq 1 ]; then local x=$(echo "scale=4; -$b / (2*$a)" | bc) echo "One real root: x = $x" else local real_part=$(echo "scale=4; -$b / (2*$a)" | bc) local imag_part=$(echo "scale=4; sqrt(-$discriminant) / (2*$a)" | bc) echo "Complex roots: x₁ = $real_part + ${imag_part}i, x₂ = $real_part - ${imag_part}i" fi } # Test cases echo "=== BASH EQUATION SOLVER ===" solve_equation 1 -3 2 echo "---" solve_equation 1 2 1 echo "---" solve_equation 1 0 1 echo "---" solve_equation 0 2 -4 echo "---" solve_equation 0 0 0 echo "---" solve_equation 0 0 5