302 lines
7.3 KiB
Markdown
302 lines
7.3 KiB
Markdown
---
|
|
author: "Devoalda"
|
|
authorEmoji: 🐺
|
|
title: "Go - Equation Solver"
|
|
date: 2020-07-12T11:20:23+08:00
|
|
description: Equation Solver with Go
|
|
draft: false
|
|
hideToc: false
|
|
enableToc: true
|
|
enableTocContent: true
|
|
tocPosition: inner
|
|
tocLevels: ["h1", "h2", "h3"]
|
|
tags:
|
|
- go
|
|
- golang
|
|
- script
|
|
- programming
|
|
series:
|
|
- Go
|
|
categories:
|
|
- Go
|
|
image: images/postImages/Formula.png
|
|
libraries:
|
|
- 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](https://golang.org/dl/)
|
|
Go Modules:
|
|
``` Golang
|
|
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
|
|
```golang
|
|
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$
|
|
|
|
``` golang
|
|
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$
|
|
|
|
```golang
|
|
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
|
|
``` golang
|
|
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
|
|
``` golang
|
|
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" >}}
|
|
<a target="_blank" href="https://icons8.com/icons/set/formula-fx">Formula FX icon</a> icon by <a target="_blank" href="https://icons8.com">Icons8</a>
|
|
{{< /expand >}}
|