Reverse bits of unit32 in go [closed] - go

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I want to flip the binary number 1000 to 0001. The bits.reverse function doesn't seem to work.
The problem is I am getting bits from a GPIO. Either 4bits or 26bits, the problem is they are in the wrong direction (1 = 1000, 2=0100 ..., also the 26bit).
Can anyone help me?
Here is my example code:
package main
import (
"fmt"
"math/bits"
)
func main() {
var x uint32 = 0b1000
fmt.Printf("%04b\n", x)
fmt.Printf("%04b\n", bits.Reverse32(x))
}

Use bits.Reverse32() to reverse the bits of a 32-bit number, but since your "useful" bits are less than 32, you have to shift right the result with the number of "useless" bits.
For example if you have 4 useful bits, after reversing those 4 bits will go to the highest 4 bits, so shift right by 32-4 = 28.
A function capturing this logic:
func reverse(x uint32, size uint32) uint32 {
return bits.Reverse32(x) >> (32 - size)
}
Example testing it:
x := uint32(0b1000)
fmt.Printf("x: %04b\n", x)
fmt.Printf("rev: %04b\n", reverse(x, 4))
x = uint32(0x3000010)
fmt.Printf("x: %026b\n", x)
fmt.Printf("rev: %026b\n", reverse(x, 26))
Output (try it on the Go Playground):
x: 1000
rev: 0001
x: 11000000000000000000010000
rev: 00001000000000000000000011

package main
import (
"fmt"
"math/bits"
)
func main() {
var x uint32 = 0b1000
fmt.Printf("%032b\n", x)
fmt.Printf("%032b\n", bits.Reverse32(x))
}
Input: 00000000000000000000000000001000
Output: 00010000000000000000000000000000
This should work. Reference: https://golang.org/pkg/math/bits/#Reverse32

Related

why float 32 and float64 printed as integer in go? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I was looking at "A Tour of Go" and saw that
package main
import (
"fmt"
"math"
)
func main() {
var x, y int = 3, 4
var f float64 = math.Sqrt(float64(x*x + y*y))
var z uint = uint(f)
fmt.Println(x, y, z, f)
}
when I run this code it prints 3 4 5 5 shouldn't it be 3 4 5 5.0 I am totally new to go looked up documentation but i couldn't find any answer for this
math.Sqrt -> float64
however you are using fmt.Println.
Try
fmt.Printf("%.1f", f)
"Println formats using the default formats for its operands and writes to standard output." https://golang.org/pkg/fmt/#Println

How to get nearest int in operation on integers in golang? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'd like to get nearest value of an operation envolving division of two integers. My initial function is like this, which always rounds to the lower integer.
func Percent(x int, y int) int {
p := x * 100 / y
return p
}
So for example when the result is 5.75, I'd like to be rounded to 6, but the above function returns 5.
I tried to use math.Round but it needs receive a float type and returns a float type. So that needs lots of conversion which gets dirty whn there are many parameters in the operation.
So I'm wondering what is the clean idomatic way to round to nearest integer?
Your operations are using all integer so the output will be an integer, so definitely you need to cast them to float first, then you can convert float to nearest int (5.75 to 5)
For that below code will work for you. You even don't need to use math.Round
func Percent(x int, y int) int {
p := float64(x * 100) / float64(y)
return int(p+0.5)
}
Just create float values from your ints, then an int value from a rounded float result:
func RoundPercent(x int, y int) int {
p := float64(x * 100) / float64(y)
return int(math.Round(p))
}

How do I element-wise square root a gonum matrix? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I was going to use Pow but it only seems to accept powering by integer values.
For example, the element-wise square root matrix m of matrix a.:
a = ⎡ 4 9⎤
⎣16 25⎦
m = ⎡2 3⎤
⎣4 5⎦
For an element-wise square root of a matrix, write something like this:
package main
import (
"fmt"
"math"
"gonum.org/v1/gonum/mat"
)
func main() {
a := mat.NewDense(2, 2, []float64{
4, 9,
16, 25,
})
fa := mat.Formatted(a, mat.Prefix(" "), mat.Squeeze())
fmt.Printf("a = %v\n\n", fa)
m := new(mat.Dense)
m.Apply(func(i, j int, v float64) float64 { return math.Sqrt(v) }, a)
fm := mat.Formatted(m, mat.Prefix(" "), mat.Squeeze())
fmt.Printf("m = %v\n\n", fm)
}
Output:
a = ⎡ 4 9⎤
⎣16 25⎦
m = ⎡2 3⎤
⎣4 5⎦

Precision loss when printing floats as strings [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
It just happened to me that if I store int number into a struct and later apply division with them. The precision would be lost.
func main() {
var x = 94911151
var y = 94911150
// If we use the value to calculate division directly, it would be fine
var result1 = float64(94911151)/94911150
var result2 = float64(x)/float64(y)
fmt.Println(result1, result2)
// If we pass the values directly as parameter into a function and then apply division, it would be fine
getParas(x,y)
// If we pass the values into a stuct, and then retrieve the value from struct, then apply division, the precision would be lost.
getLinearParas(Point{x,y},Point{0,0})
}
func getParas(a int, b int){
diffX := a -0
diffY := b-0
c:= float64(diffX) / float64(diffY)
fmt.Println(c)
}
type Point struct{
X int
Y int
}
func getLinearParas(point1 Point, point2 Point) {
diffX := point1.X - point2.X
diffY := point1.Y - point2.Y
a := float64(diffX) / float64(diffY)
fmt.Printf("diffY: %d; diffX:%d ; a:%f \n", diffY, diffX, a)
}
Like the code, If I put int values into a struct, and later apply division on them. the precision would be lost somehow.
The result of running above code is
1.00000001053617 1.00000001053617
1.00000001053617
diffY: 94911150; diffX:94911151 ; a:1.000000
Or you can try it yourself in playground
https://play.golang.org/p/IDS18rfv9e6
Could anyone explain why this happens? and how to avoid such loss?
Thank you very much.
Change %f in the format string to %v or %g or %.14f. fmt.Println prints things with the equivalent of %v, %v for float64 is treated as %g. %f prints values with 6 significant digits by default, %g uses "the smallest number of digits necessary to identify the value uniquely".

Float Accuracy in Go [duplicate]

This question already has answers here:
Why are floating point numbers inaccurate?
(5 answers)
Closed 2 years ago.
This question is a follow on from a previous question I asked. The answers I received suggested that I make use of the Go math.Big library. In this question I use the library but unfortunately to little effect.
I am trying to using the Binet formula to calculate fib(100). I am using
Go's Big.Float but without success. I get accuracy to about 10 decimal
places. Please advise.
I am trying to avoid loops/recursion as I think these approaches will
not scale well. Hence my attempt to leverage Binet's formula
// currently produces inaccurate results as the input increases.
package main
import (
"fmt"
"math/big"
"math"
"strconv"
)
func fib(n int) float64 {
var sroot5 = new(big.Float).SetPrec(200).SetFloat64(2.236067977499789696409173668731276235440618359611525724270897)
var phi = new(big.Float).SetPrec(200).SetFloat64(1.61803398874989484820458683436563811772030917980576286213544862)
var minusPhi = new(big.Float).SetPrec(200).SetFloat64(-0.61803398874989484820458683436563811772030917980576)
var fltP float64;
fltP, _ = phi.Float64()
var fltN float64;
fltN, _ = minusPhi.Float64()
var denom float64
denom, _ = sroot5.Float64()
// Magic fib formula (Binet) is:
// (Phi ^ n - (-phi ^ n)) / sqrt(5)
z := (math.Pow(fltP, float64(n)) - math.Pow(fltN, float64(n))) / denom
return math.Ceil(z)
}
func main() {
fib(100)
fmt.Println(strconv.FormatFloat(fib(100), 'f', 0, 64))
fmt.Println("true answer of fib(100) should be -> 354224848179261915075")
}
You are using IEEE 754 64-bit floating point.
In Go, to calculate fib(100) accurately you could simply say:
package main
import (
"fmt"
"math/big"
)
func fib(n int) *big.Int {
f := big.NewInt(0)
a, b := big.NewInt(0), big.NewInt(1)
for i := 0; i <= n; i++ {
f.Set(a)
a.Set(b)
b.Add(f, b)
}
return f
}
func main() {
fmt.Println(fib(100))
}
Output:
354224848179261915075

Resources