awk — Quadratics & Polynomials

Quadratic formula — solve ax² + bx + c = 0
# 2x² + 5x - 3 = 0
awk 'BEGIN{
    a=2; b=5; c=-3
    disc=b^2-4*a*c
    if(disc<0) print "no real roots"
    else if(disc==0) printf "one root: x=%.4f\n", -b/(2*a)
    else{
        x1=(-b+sqrt(disc))/(2*a)
        x2=(-b-sqrt(disc))/(2*a)
        printf "x1=%.4f x2=%.4f\n", x1, x2
    }
}'
# x1=0.5000 x2=-3.0000
Discriminant analysis — classify roots
cat <<'EOF' | awk -F, '{
    a=$1; b=$2; c=$3
    disc=b^2-4*a*c
    if(disc>0) type="two real"
    else if(disc==0) type="one repeated"
    else type="complex"
    printf "%dx² + %dx + %d → disc=%.0f (%s)\n", a, b, c, disc, type
}'
1,5,6
1,4,4
1,1,1
EOF
Vertex form — find vertex of parabola
# ax² + bx + c → vertex at (-b/2a, f(-b/2a))
awk 'BEGIN{
    a=2; b=-8; c=6
    h=-b/(2*a)
    k=a*h^2+b*h+c
    printf "vertex: (%.2f, %.2f)\n", h, k
    printf "axis of symmetry: x=%.2f\n", h
    printf "opens %s\n", (a>0?"upward":"downward")
}'
Evaluate polynomial at a point — Horner’s method
# 3x³ + 2x² - 5x + 7 at x=4
# coefficients: highest degree first
echo "3 2 -5 7" | awk '{
    x=4; result=$1
    for(i=2;i<=NF;i++) result=result*x+$i
    printf "p(%d) = %d\n", x, result
}'
# p(4) = 3*64 + 2*16 - 5*4 + 7 = 219
Complete the square — ax² + bx + c → a(x-h)² + k
awk 'BEGIN{
    a=3; b=12; c=7
    h=-b/(2*a)
    k=c-b^2/(4*a)
    printf "%dx² + %dx + %d = %d(x %s %.2f)² + %.2f\n",
        a, b, c, a, (h>=0?"- ":"+ "), (h>=0?h:-h), k
}'
Sum and product of roots (Vieta’s formulas)
awk 'BEGIN{
    a=2; b=-7; c=3
    printf "sum of roots = %.4f  (-b/a)\n", -b/a
    printf "product of roots = %.4f  (c/a)\n", c/a
    # verify
    disc=b^2-4*a*c
    x1=(-b+sqrt(disc))/(2*a); x2=(-b-sqrt(disc))/(2*a)
    printf "actual roots: x1=%.4f x2=%.4f\n", x1, x2
    printf "actual sum=%.4f product=%.4f\n", x1+x2, x1*x2
}'
Generate truth table for polynomial values
# Evaluate x² - 4x + 3 for x = -2 to 6
awk 'BEGIN{
    printf "%4s %8s\n", "x", "f(x)"
    printf "%4s %8s\n", "---", "-----"
    for(x=-2;x<=6;x++){
        fx=x^2-4*x+3
        printf "%4d %8d\n", x, fx
    }
}'
Find roots of cubic — Cardano’s method (depressed cubic)
# x³ - 6x² + 11x - 6 = 0 (roots: 1, 2, 3)
awk 'BEGIN{
    # convert ax³+bx²+cx+d to depressed: t³+pt+q
    a=1; b=-6; c=11; d=-6
    p=(3*a*c-b^2)/(3*a^2)
    q=(2*b^3-9*a*b*c+27*a^2*d)/(27*a^3)
    disc=-(4*p^3+27*q^2)
    printf "p=%.4f q=%.4f discriminant=%.4f\n", p, q, disc
    if(disc>0) print "three real roots"
    else if(disc==0) print "repeated root"
    else print "one real + two complex"
}'
Batch solve quadratics from heredoc
cat <<'EOF' | awk -F, '{
    a=$1; b=$2; c=$3
    disc=b^2-4*a*c
    printf "%dx²%+dx%+d = 0 → ", a, b, c
    if(disc<0) printf "complex roots\n"
    else if(disc==0) printf "x=%.2f\n", -b/(2*a)
    else printf "x=%.2f, x=%.2f\n", (-b+sqrt(disc))/(2*a), (-b-sqrt(disc))/(2*a)
}'
1,-5,6
1,2,1
2,3,5
3,-12,9
EOF