Equation Solver in Go!

Equation Solver in Go!
Photo by Mohammad Rahmani / Unsplash

Introduction

This is a simple linear and quadratic equation solver in the terminal done in go.

Equation in the form of

The program will first ask for type of equation, followed by getting the coefficients of each equation.

Dependencies

  • Go
    Go Modules:
import (
	"fmt"
	"math"
	"os"
	"strconv"
)

Code

Create a new project, and make a new file named main.go.
Ensure that project path is in $GOPATH, this can be checked in your shell with echo $GOPATH

FloatToString Method

This program uses floating points to allow for fractions and decimal numbers in the calculation. This method converts float to string

func FloatToString(input_num float64) string {
	// to convert a float number to a string
	return strconv.FormatFloat(input_num, 'f', 3, 64)
}

This method will be used throughout the program.

Linear Equation Solver

This equation:

would be easy to solve by rearranging the function into

solving it with this equation:

func linearEqn() {
  // Declare coefficients
	var a, b, c, d float64

	fmt.Println("Linear Equation Solver")
	fmt.Println("Eqation in the form of ax + b = cx + d ")

  // Scan and check for null or empty values
	_, err := fmt.Scan(&a, &b, &c, &d)
	if err != nil {
		panic(err)
	}

	if a == c && b == d {
		fmt.Println("There are infinite solutions to this equation")
	} else if a == c {
		fmt.Println("This equations are parallel to each other, hence no root")
	} else {
		x := (d - b) / (a - c)
		y := a*x + b
		fmt.Println("Equation: (" + FloatToString(a) + ")x + (" + FloatToString(b) + ") = (" + FloatToString(c) + ")x + (" + FloatToString(d) + ")")
		fmt.Println("The value of x:", x)
		fmt.Printf("OR the line intersects at (%g,%g)\n", x, y)

	}
}

Quadratic Equation Solver

A Quadratic equation in the form of

can be solved with the following equation:


The program will first solve for the discriminant

to determine the number of roots, and thereafter solve for the roots of the equation where

func quadraticEqn() {
	var a, b, c float64

	fmt.Println("Quadric Equation Solver")
	fmt.Println("Equation in the form of ax^2+bx+c = 0")
	fmt.Println("Where a > 0")
	fmt.Println()
	fmt.Println("Enter a, b, c, each in a new line:")

	// Scan and check for null or empty variables
	_, err := fmt.Scan(&a, &b, &c)
	if err != nil {
		panic(err)
	}

  // Panic if coefficient of x^2 <= 0
	if a <= 0.0 {
		panic("Coefficient of a cannot be <= 0")
	} else {

		eqn := "(" + FloatToString(a) + ")x^2 +(" + FloatToString(b) + ")x +(" + FloatToString(c) + ")"
		fmt.Println("Equation:", eqn)
		fmt.Println("a:", a)
		fmt.Println("b:", b)
		fmt.Println("c:", c)

    // Solve of discriminant
		discriminant := b*b - 4*a*c
		fmt.Println("Discriminant:", discriminant)

		if discriminant < 0 {
			// No Real Roots
			fmt.Println("Equation has no real roots")

		} else if discriminant == 0 {
			// 1 real root
			alpha := (-b + math.Sqrt(discriminant)) / (2.0 * a)
			fmt.Printf("x = %g\n", alpha)

		} else {
			//2 real roots
			alpha := (-b + math.Sqrt(discriminant)) / (2.0 * a)
			beta := (-b - math.Sqrt(discriminant)) / (2.0 * a)
			fmt.Printf("x = %g or x = %g\n", alpha, beta)

		}

	}

}

Main method

This will be the Terminal UI(TUI) to get users to choose the type of equation

func main() {
	fmt.Println("Equation Solver by Devoalda")
	fmt.Println("Enter type of equation:")
	fmt.Println("1. Linear Equation (ax + b = cx + d)")
	fmt.Println("2. Quadratic Equation (ax^2 + bx + c = 0)")

	//Single Variable scan
	var choice int
	_, err := fmt.Scanf("%d", &choice)
	if err != nil {
		panic(err)
	}

	//Switch case
	switch choice {
	case 1:
		linearEqn()
	case 2:
		quadraticEqn()
	default:
		fmt.Println("Unrecognised choice, quitting program now!")
		os.Exit(3)
	}
}

Summary

The Program can be executed with go run main.go. All coefficients can be integers or floats.

Full Code

package main

import (
	"fmt"
	"math"
	"os"
	"strconv"
)

func main() {
	fmt.Println("Equation Solver by Devoalda")
	fmt.Println("Enter type of equation:")
	fmt.Println("1. Linear Equation (ax + b = cx + d)")
	fmt.Println("2. Quadratic Equation (ax^2 + bx + c = 0)")

	//Single Variable scan
	var choice int
	_, err := fmt.Scanf("%d", &choice)
	if err != nil {
		panic(err)
	}

	//Switch case
	switch choice {
	case 1:
		linearEqn()
	case 2:
		quadraticEqn()
	default:
		fmt.Println("Unrecognised choice, quitting program now!")
		os.Exit(3)
	}
}

func linearEqn() {
	var a, b, c, d float64

	fmt.Println("Linear Equation Solver")
	fmt.Println("Eqation in the form of ax + b = cx + d ")

	_, err := fmt.Scan(&a, &b, &c, &d)
	if err != nil {
		panic(err)
	}

	if a == c && b == d {
		fmt.Println("There are infinite solutions to this equation")
	} else if a == c {
		fmt.Println("This equations are parallel to each other, hence no root")
	} else {
		x := (d - b) / (a - c)
		y := a*x + b
		fmt.Println("Equation: (" + FloatToString(a) + ")x + (" + FloatToString(b) + ") = (" + FloatToString(c) + ")x + (" + FloatToString(d) + ")")
		fmt.Println("The value of x:", x)
		fmt.Printf("OR the line intersects at (%g,%g)\n", x, y)

	}
}

func quadraticEqn() {
	var a, b, c float64

	fmt.Println("Quadric Equation Solver")
	fmt.Println("Equation in the form of ax^2+bx+c = 0")
	fmt.Println("Where a > 0")
	fmt.Println()
	fmt.Println("Enter a, b, c, each in a new line:")

	_, err := fmt.Scan(&a, &b, &c)
	if err != nil {
		panic(err)
	}

	if a <= 0.0 {
		panic("Coefficient of a cannot be <= 0")
	} else {

		eqn := "(" + FloatToString(a) + ")x^2 +(" + FloatToString(b) + ")x +(" + FloatToString(c) + ")"
		fmt.Println("Equation:", eqn)
		fmt.Println("a:", a)
		fmt.Println("b:", b)
		fmt.Println("c:", c)

		discriminant := b*b - 4*a*c
		fmt.Println("Discriminant:", discriminant)

		if discriminant < 0 {
			// No Real Roots
			fmt.Println("Equation has no real roots")

		} else if discriminant == 0 {
			// 1 real root
			alpha := (-b + math.Sqrt(discriminant)) / (2.0 * a)
			fmt.Printf("x = %g\n", alpha)

		} else {
			//2 real roots
			alpha := (-b + math.Sqrt(discriminant)) / (2.0 * a)
			beta := (-b - math.Sqrt(discriminant)) / (2.0 * a)
			fmt.Printf("x = %g or x = %g\n", alpha, beta)

		}

	}

}

func FloatToString(input_num float64) string {
	// to convert a float number to a string
	return strconv.FormatFloat(input_num, 'f', 3, 64)
}

Building the program

Build the go project at the project root with the command go build
If $GOPATH is in your $PATH, you can run the program with the program name eqn
The compiled binary is located in $GOROOT/bin/, where you can run the program with ./eqn