Why do floats and ints = Nan? in go - go

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 \n", b2)
ac := float64(4)*float64(a)*float64(c)
fmt.Printf("%.2f \n", ac)
fmt.Printf("%.2f \n", 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

Related

golang calculate full precision float number

Used a decimal point of 200 as the precision, I need to calculate a number from atto to decimal number similar screenshot.
To get the values at precision of nano and atto you can use %.9f and %.18f in fmt.Printf() respectively,I created a small program to get your value of 0.000000000000099707 as follows:
package main
import (
"fmt"
"math"
)
func main() {
powr := math.Pow(10, -18)
numb := 99707 * powr
fmt.Println("number", numb)
fmt.Printf("\nthe value in atto %.18f\n", numb)
}
Output:
number 9.970700000000001e-14
the value in atto 0.000000000000099707
You can use the github.com/shopspring/decimal package for this as well. This library can represents numbers up to 2^31 (2147483648) digits. Here is a simple code to do the calculation:
d := decimal.NewFromInt(99707)
d10 := decimal.NewFromInt(10)
dpow := decimal.NewFromInt(-18)
d10pow := d10.Pow(dpow)
dmul := d.Mul(d10pow)
fmt.Println(dmul)
This can simplified to:
d := decimal.NewFromInt(99707).Mul(decimal.NewFromInt(10).Pow(decimal.NewFromInt(-18)))
fmt.Println(d)
Output: 0.000000000000099707
See playground
I was interested in how to do this so I found the apd package from cockroach that handles arbitrary precision calculations. You can use it like this:
import (
"fmt"
"github.com/cockroachdb/apd"
)
func main() {
// 99707 * 10^(-18)
n1 := apd.New(99707, 0)
n2 := apd.New(10, 0)
n3 := apd.New(-18, 0)
c := apd.BaseContext.WithPrecision(200)
res := apd.New(0,0)
ctx, err := c.Pow(res, n2, n3)
if err != nil {
panic(err)
}
ctx, err = c.Mul(res, res, n1)
if err != nil {
panic(err)
}
fmt.Println(ctx.Inexact(), res.Text('f'))
}
And it will output:
false 0.000000000000099707
You will have to be careful with the loss of precision that may happen and look at the inexact field.

Bridge and Torch Problem for 'n' people with Go [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Problem: Given an array of positive distinct integer denoting the crossing time of ‘n’ people. These ‘n’ people are standing at one side of bridge. Bridge can hold at max two people at a time. When two people cross the bridge, they must move at the slower person’s pace. Find the minimum total time in which all persons can cross the bridge.
I am not able to find the pattern as of how to scale this for 'n' people. But somehow I managed to find the case with 4 people. Can someone help me with this. I am new to Golang and I am stuck with this problem.
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"sort"
"gopkg.in/yaml.v2"
)
type conf struct {
Person []map[string]float32 `yaml:"person"`
}
func (c *conf) getConf() *conf {
filename := os.Args[1] // Taking file input
yamlFile, err := ioutil.ReadFile(filename) // Yaml parse
if err != nil {
log.Printf("yamlFile.Get err #%v ", err)
}
err = yaml.Unmarshal(yamlFile, c)
if err != nil {
log.Fatalf("Unmarshal: %v", err)
}
return c
}
func main() {
var c conf // Object of struct conf
c.getConf() // calling getConf function
// Sorting the current conf map
n := map[float32][]string{} // Map to store current conf map
var a []float32 // Store values from conf map
for k, v := range c.Person {
v := float32(v)
fmt.Println(k, v)
n[v] = append(n[v], k)
}
for k := range n {
a = append(a, k)
}
// Converting float32 as float64 in order to sort the values in conf map
float32AsFloat64Values := make([]float64, len(a))
for i, val := range a {
float32AsFloat64Values[i] = float64(val)
}
sort.Float64s(float32AsFloat64Values)
for i, val := range float32AsFloat64Values {
a[i] = float32(val)
}
var time float32
fmt.Printf("\n%v\n", a)
for _, k := range a {
min1 := a[0]
min2 := a[1]
min3 := a[2]
for _, s := range n[k] {
//Debug:
fmt.Printf("%s, %g\n", s, k)
if len(a) > 3 {
time = (3 * min2) + min1 + a[3] //Formula for minimum time in case of 4 people
} else if len(a) == 3 {
time = min1 + min2 + min3
} else {
fmt.Println("Enter valid arguments in config.yaml")
}
}
}
fmt.Printf("Minimum time taken to cross the bridge is:\t%g\n", time)
}
Playground: https://play.golang.org/p/ObTVA8gk0mg
Config.yaml is:
person:
person_1: 2
person_2: 1
person_3: 5
person_4: 8
person_5: 9
One could run this as: 'go run main.go config.yaml'.
My scenario is that there could be 4,5 or 'n' number of people given in this yaml. Then what would be the minimum time for them to cross the bridge given the constraints.
I think the original problem is a bit more interesting than the one stated (yes, there has to be a Torch in the "Bridge and Torch" problem!).
Based on the Wikipedia description, for example,
Four people come to a river in the night. There is a narrow bridge, but it can only hold two people at a time. They have one torch and, because it's night, the torch has to be used when crossing the bridge. Person A can cross the bridge in 1 minute, B in 2 minutes, C in 5 minutes, and D in 8 minutes. When two people cross the bridge together, they must move at the slower person's pace. The question is, can they all get across the bridge if the torch lasts only 15 minutes?
In our case, of course, there are N people instead of just four, and it takes them variable amount of time to cross the bridge, but the rest of the story is the same.
Here's the implementation:
import (
"fmt"
"sort"
)
func minCrossingTime(x []int) int {
if len(x) == 1 {
return x[0]
}
sort.Ints(x)
t := 0
a, b := x[0], x[1]
x = x[2:]
for len(x) >= 2 {
n := len(x)
c, d := x[n-2], x[n-1]
x = x[:n-2]
t1 := 2*b + a + d
t2 := d + c + 2*a
if t1 < t2 {
t += t1
} else {
t += t2
}
}
if len(x) == 1 {
c := x[0]
t += a + b + c
} else {
t += b
}
return t
}
func main() {
x1 := []int{1, 2, 5, 8}
fmt.Printf("x = %x, time = %d\n", x1, minCrossingTime(x1))
x2 := []int{3, 8, 1, 6, 2, 9}
fmt.Printf("x = %x, time = %d\n", x2, minCrossingTime(x2))
}
Output:
x = [1 2 5 8], time = 15
x = [1 2 3 6 8 9], time = 27
Note: the first example [1 2 5 8] is straight from the Wikipedia, so the answer is yes, they can cross in 15 minutes
Key idea:
Definitions:
Let X = [X1,X2,...,XN] be the sorted array of crossing times with X1 being the fastest and XN the slowest
Let's denote as {XI,XJ} crossing by the pair of people XI and XJ, and {XK} crossing by one person XK, with +{...} indicating the crossing in the desired direction and -{...} in the opposite direction
Logic:
If N < 4 the problem is trivial:
N = 1 => t = X1 (+{X1})
N = 2 => t = X2 (+{X1,X2})
N = 3 => t = X1 + X2 + X3 (+{X1,X2} -{X1} + {X1,X3})
If N >= 4 consider the following problem: how to make two slowest people (and only them) cross the bridge and have the torch brought back in minimal time. There are two "good" ways to do it, with times
t1 = X1 + 2*X2 + XN (+{X1,X2} -{X1} +{X[N-1],XN} -{X2}) and
t2 = 2*X1 + X[N-1] + XN (+{X1,X[N-1]} -{X1} +{X1,XN} -{X1}), so we choose the best (minimum) out of these two
Now the two slowest have crossed the bridge, and the torch is on the same side where it started, so we are left with the original problem for X' = [X1, X2, ..., X[N-2]], which can be solved iteratively by applying the same logic and summing up the crossing times
Extras:
For mathematical proof and more context see e.g. https://page.mi.fu-berlin.de/rote/Papers/pdf/Crossing+the+bridge+at+night.pdf
Code golf solutions in different programming languages: https://codegolf.stackexchange.com/questions/75615/the-bridge-and-torch-problem
Problem: Given an array of positive distinct integer denoting the
crossing time of ‘n’ people. These ‘n’ people are standing at one side
of bridge. Bridge can hold at max two people at a time. When two
people cross the bridge, they must move at the slower person’s pace.
Find the minimum total time in which all persons can cross the bridge.
person:
person_1: 2
person_2: 1
person_3: 5
person_4: 8
person_5: 9
Your algorithm looks complicated.
For example,
package main
import (
"fmt"
"sort"
)
func minCrossingTime(people []int) int {
sort.Slice(people, func(i, j int) bool {
return people[i] > people[j]
})
min := 0
for i := 0; i < len(people); i += 2 {
min += people[i]
}
return min
}
func main() {
people := []int{2, 1, 5, 8, 9}
fmt.Println(len(people), people)
crossingTime := minCrossingTime(people)
fmt.Println(len(people), people)
fmt.Println(crossingTime)
}
Playground: https://play.golang.org/p/pXdGcinwxr-
Output:
5 [2 1 5 8 9]
5 [9 8 5 2 1]
15

How to unpack 2, 2 and 3 bits out of a byte

Assuming I have 3 bytes (2x2bits and 1x3bits) packed like this:
func pack(a, b, c byte) byte { // is there a more efficient way to pack them?
return a<<6 | b<<4 | c
}
func main() {
v := pack(1, 2, 6)
a := v >> 6
b := v >> 4 // wrong
c := v & 7
fmt.Println(v, a, b, c)
}
How do I unpack b?
You need to mask off the unused bits like you've already done for c. I also added masks to the pack function, to prevent accidental overlapping of values:
const (
threeBits = 0x7
twoBits = 0x3
)
func pack(a, b, c byte) byte {
return a<<6 | b&twoBits<<4 | c&threeBits
}
func main() {
v := pack(1, 2, 6)
a := v >> 6
b := v >> 4 & twoBits
c := v & threeBits
fmt.Println(v, a, b, c)
}

golang - modulus using math big package

Reading up the documentation - http://golang.org/pkg/math/big/
Mod sets z to the modulus x%y for y != 0 and returns z. If y == 0, a division-by-zero run-time panic occurs. Mod implements Euclidean modulus (unlike Go); see DivMod for more details.
10%4 = 2 but I get 8 with this (using the math/big package to do the same thing) - http://play.golang.org/p/_86etDvLYq
package main
import "fmt"
import "math/big"
import "strconv"
func main() {
ten := new(big.Int)
ten.SetBytes([]byte(strconv.Itoa(10)))
four := new(big.Int)
four.SetBytes([]byte(strconv.Itoa(4)))
tenmodfour := new(big.Int)
tenmodfour = tenmodfour.Mod(ten, four)
fmt.Println("mod", tenmodfour)
}
I most likely got something wrong. Where's the mistake?
It's because SetBytes is not doing what you think! Use SetInt64 instead.
ten := new(big.Int)
ten.SetBytes([]byte(strconv.Itoa(10)))
four := new(big.Int)
four.SetBytes([]byte(strconv.Itoa(4)))
fmt.Println(ten, four)
Result:
12592 52
And indeed, 12592%52 == 8
If you want to use numbers bigger than what int64 lets you manipulate, you can also use the SetString function:
n := new(big.Int)
n.SetString("456135478645413786350", 10)
Just an addition to julienc's answer, if you were to use SetBytes, you have to convert the number to bytes like this :
func int2bytes(num int) (b []byte) {
b = make([]byte, 4)
binary.BigEndian.PutUint32(b, uint32(num))
return
}
func main() {
ten := new(big.Int)
ten.SetBytes(int2bytes(10))
four := new(big.Int)
four.SetBytes(int2bytes(4))
fmt.Println(ten, four)
tenmodfour := new(big.Int)
tenmodfour = tenmodfour.Mod(ten, four)
fmt.Println("mod", tenmodfour)
}

Generate all possible n-character passwords

As part of a learning-Go exercise, I'm writing a simplistic brute-force password cracker.
To generate all possible 2-character passwords that use the characters A-E in Python, I would use itertools.product():
from itertools import product
for permutation in product('ABCDE', repeat=2):
print permutation
However, I'm struggling to do this in Go.
Other questions seem to be about permutations, which isn't quite what I want. And while the Python docs include a sample implementation of the function, I don't know how to translate yield into Go.
I suppose I should mention two restrictions:
I'd like the length of the password to be variable. That is, I may want to do 8-character passwords, or 6-character, or something else. This means we can't just nest n loops.
I don't want to have all of them in memory at once.
What you want is basically the n-ary cartesian product of a set with itself. So for all 3-character passwords you want Prod(set,set,set). This can be constructed iteratively. First construct the n-1 product, then for each product and each element of the initial set, add the element. So for instance all 2 character passwords -> 3 character passwords where the only valid characters are 'a' or 'b'.
"ab" = {a,b} -> {(a,a),(a,b),(b,a),(b,b)} -> {(a,a,a),(a,a,b),(a,b,a),(a,b,b),(b,a,a),(b,a,b),(b,b,a),(b,b,b)}
func NAryProduct(input string, n int) []string {
if n <= 0 {
return nil
}
// Copy input into initial product set -- a set of
// one character sets
prod := make([]string, len(input))
for i, char := range input {
prod[i] = string(char)
}
for i := 1; i < n; i++ {
// The bigger product should be the size of the input times the size of
// the n-1 size product
next := make([]string, 0, len(input)*len(prod))
// Add each char to each word and add it to the new set
for _, word := range prod {
for _, char := range input {
next = append(next, word + string(char))
}
}
prod = next
}
return prod
}
Playground version: http://play.golang.org/p/6LhApeJ1bv
It should be noted that there's a lot of room for improvement on this solution. If you want to construct all passwords of length, say, 6-18, calling this method independently for each one will recalculate previously computed sets. I'll leave writing the better version up to you. Given what I've shown you, it shouldn't be too difficult to modify the code to take an arbitrary (n-m)ary product and compute the n-ary product from it. (Hint: think about how you'd do this recursively)
For example, satisfying your restrictions,
package main
import "fmt"
func nextPassword(n int, c string) func() string {
r := []rune(c)
p := make([]rune, n)
x := make([]int, len(p))
return func() string {
p := p[:len(x)]
for i, xi := range x {
p[i] = r[xi]
}
for i := len(x) - 1; i >= 0; i-- {
x[i]++
if x[i] < len(r) {
break
}
x[i] = 0
if i <= 0 {
x = x[0:0]
break
}
}
return string(p)
}
}
func main() {
np := nextPassword(2, "ABCDE")
for {
pwd := np()
if len(pwd) == 0 {
break
}
fmt.Println(pwd)
}
}
Output:
AA
AB
AC
AD
AE
BA
BB
BC
BD
BE
CA
CB
CC
CD
CE
DA
DB
DC
DD
DE
EA
EB
EC
ED
EE
package main
import (
"fmt"
"strings"
"strconv"
// permutation and combination of charactersList
"github.com/ernestosuarez/itertools"
)
func main() {
passwordLength := "1,2,4"
characters := "abcdefghijklmnopqrstuvwxyz0123456789!##$%^&*()+-./"
passwordLengthList := strings.Split(passwordLength, ",")
charactersList := strings.Split(characters, "")
for _, passLen := range passwordLengthList {
passLenInt, err := strconv.Atoi(passLen)
if err != nil {
panic(err)
}
for v := range itertools.PermutationsStr(charactersList, passLenInt) {
fmt.Println(strings.Join(v, ""))
}
}
}
uses select for channels to generate unique passwords
func randombitsGen(l int) (out chan string) {
Capschar := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
smallchar := "abcdefghijklmnopqrstuvwxyz"
nums := "0123456789"
specials := "!##$%ˆ&*()?><"
out = make(chan string, l)
defer close(out)
for {
select {
case out <- string(Capschar[rand.Intn(len(strings.Split(Capschar, "")))]):
case out <- string(Capschar[rand.Intn(len(strings.Split(Capschar, "")))]):
case out <- string(Capschar[rand.Intn(len(strings.Split(Capschar, "")))]):
case out <- string(smallchar[rand.Intn(len(strings.Split(smallchar, "")))]):
case out <- string(smallchar[rand.Intn(len(strings.Split(smallchar, "")))]):
case out <- string(smallchar[rand.Intn(len(strings.Split(smallchar, "")))]):
case out <- string(nums[rand.Intn(len(strings.Split(nums, "")))]):
case out <- string(specials[rand.Intn(len(strings.Split(specials, "")))]):
default:
return
}
}
}

Resources