package main
import (
"fmt"
"math"
)
func main() {
// x= +- sqrtB-4ac/2a
cal()
}
func cal() {
b := 3
a := 4
c := 2
b2 := float64(b*b)
ac := float64(4)*float64(a)*float64(c)
q := math.Sqrt(b2-ac)
fmt.Print(q)
}
This will output a NaN, but why. I am trying to make a quadratic calculator. All I want is for this to output the number.
Because you're trying to take the square root of a negative number which isn't a valid operation (not just in Go, in math) and so it returns NaN which is an acronym for Not A Number.
b := 3
a := 4
c := 2
b2 := float64(b*b) // sets b2 == 9
ac := float64(4)*float64(a)*float64(c) // ac == 32
q := math.Sqrt(b2-ac) // Sqrt(9-32) == Sqrt(-23) == NaN
fmt.Print(q)
q = math.Sqrt(math.Abs(b2-ac)) // suggested in comments does Sqrt(23) == ~4.79
// perhaps the outcome you're looking for.
EDIT: please don't argue semantics on the math bit. If you want to discuss square roots of negative numbers this isn't the place. Generally speaking, it is not possible to take the square root of a negative number.
Since you're taking the square root of a negative number, you've got an imaginary result (sqrt(-9) == 3i
). This is assuredly NOT what you're trying to do. Instead, do:
func main() {
b := float64(3)
a := float64(4)
c := float64(2)
result := [2]float64{(-b + math.Sqrt(math.Abs(b*b - 4*a*c))) / 2 * a,
(-b - math.Sqrt(math.Abs(b*b - 4*a*c))) / 2 * a)}
fmt.Println(result)
}
You try Sqrt Negative Number for this reason return always NaN ( Not a Number ) I run you code and print the results:
b := 3
a := 4
c := 2
b2 := float64(b*b)
fmt.Printf("%.2f
", b2)
ac := float64(4)*float64(a)*float64(c)
fmt.Printf("%.2f
", ac)
fmt.Printf("%.2f
", b2-ac)
q := math.Sqrt(b2-ac)
fmt.Print(q)
Console: 9.00 32.00 -23.00 NaN
Sqrt in Golang : https://golang.org/pkg/math/#Sqrt