devoalda.gitlab.io/content/en/posts/equation_solver.md

7.3 KiB

author authorEmoji title date description draft hideToc enableToc enableTocContent tocPosition tocLevels tags series categories image libraries
Devoalda 🐺 Go - Equation Solver 2020-07-12T11:20:23+08:00 Equation Solver with Go false false true true inner
h1
h2
h3
go
golang
script
programming
Go
Go
images/postImages/Formula.png
mathjax

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:
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

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

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

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 {{< expand "Credits" >}} Formula FX icon icon by Icons8 {{< /expand >}}