This page looks best with JavaScript enabled

Go - Equation Solver

 ·  ☕ 7 min read  ·  🐺 Devoalda

Introduction

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

Equation in the form of $ax + b = cx + d$ or $ax^2 + bx + c = 0$

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

Dependencies

  • Go
    Go Modules:
1
2
3
4
5
6
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

1
2
3
4
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

Equation of $ax + b = cx +d$ would be easy to solve by rearranging the function into $(a - c)x = d - b$, solving it with this equation: $$x = {d - b \over a - c}$$ Where $a \ne c$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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 $ax^2 + bx + c = 0$, can be solved with the following equation: $$x = {-b \pm \sqrt{b^2-4ac} \over 2a}$$
The program will first solve for the discriminant $b^2 - 4ac$ to determine the number of roots, and thereafter solve for the roots of the equation where the $discriminant \ge 0$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
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

Share on

Devoalda
WRITTEN BY
Devoalda
Technophile