big.Float GetString without rounding - go

I want to see the result: "3891113451447590234" without "3891113451447590400"
bigI,_ := big.NewInt(0).SetString("3891113451447590234", 10)
bigF := big.NewFloat(0).SetInt(bigI)
fmt.Println(bigF)
fmt.Println(bigF.String())
fmt.Println(bigF.SetMode(big.AwayFromZero).Text('f', 8))
fmt.Println(bigF.SetMode(big.AwayFromZero).Text('g', 20))
3.8911134514475904e+18
3.891113451e+18
3891113451447590400.00000000
3891113451447590400

The big.NewFloat function sets the default precision to 53.
NewFloat allocates and returns a new Float set to x, with precision 53 and rounding mode ToNearestEven. NewFloat panics with ErrNaN if x is a NaN.
If you want to set values with higher precision, you can set the precision directly, or you can start with precision 0 using a zero value of big.Float which determines the required precision when the value is first set.
f1, _, _ := new(big.Float).SetPrec(128).SetMode(big.ToNearestEven).Parse("3891113451447590234", 10)
// equivalent to
// big.ParseFloat("3891113451447590234", 10, 128, big.ToZero)
fmt.Println(f1)
// 3.891113451447590234e+18
i, _ = new(big.Int).SetString("3891113451447590234", 10)
f2 = new(big.Float).SetInt(i)
fmt.Println(f2)
// 3.891113451447590234e+18

Related

How to coerce math.Inf to an integer?

I've got some code I'm using to do comparisons, and I want to start with infinite values. Here's a snippet of my code.
import (
"fmt"
"math"
)
func snippet(arr []int) {
least := int(math.Inf(1))
greatest := int(math.Inf(-1))
fmt.Println("least", math.Inf(1), least)
fmt.Println("greatest", math.Inf(-1), greatest)
}
and here's the output I get from the console
least +Inf -9223372036854775808
greatest -Inf -9223372036854775808
why is +Inf coerced into a negative int ?
Infinity is not representable by int.
According to the go spec,
In all non-constant conversions involving floating-point or complex values, if the result type cannot represent the value the conversion succeeds but the result value is implementation-dependent.
Maybe you are looking for the largest representable int? How to get it is explained here.
math.Inf() returns an IEEE double-precision float representing positive infinity if the sign of the argument is >= 0, and negative infinity if the sign is < 0, so your code is incorrect.
But, the Go language specifiction (always good to read the specifications) says this:
Conversions between numeric types
.
.
.
In all non-constant conversions involving floating-point or complex values,
if the result type cannot represent the value the conversion succeeds but
the result value is implementation-dependent.
Two's complement integer values don't have the concept of infinity, so the result is implementation dependent.
Myself, I'd have expected to get the largest or smallest integer value for the integer type the cast is targeting, but apparently that's not the case.
This looks to the runtime source file responsible for the conversion, https://go.dev/src/runtime/softfloat64.go
And this is the actual source code.
Note that an IEEE-754 double-precision float is a 64-bit double word, consisting of
a sign bit, the high-order (most significant/leftmost bit), 0 indicating positive, 1 indicating negative.
an exponent (biased), consisting of the next 11 bits, and
a mantissa, consisting of the remaining 52 bits, which can be denormalized.
Positive Infinity is a special value with a sign bit of 0, a exponent of all 1 bits, and a mantissa of all 0 bits:
0 11111111111 0000000000000000000000000000000000000000000000000000
or 0x7FF0000000000000.
Negative infinity is the same, with the exception that the sign bit is 1:
1 11111111111 0000000000000000000000000000000000000000000000000000
or 0xFFF0000000000000.
Looks like `funpack64() returns 5 values:
a uint64 representing the sign (0 or the very large non-zero value 0x8000000000000000),
a uint64 representing the normalized mantissa,
an int representing the exponent,
a bool indicating whether or not this is +/- infinity, and
a bool indicating whether or not this is NaN.
From that, you should be able to figure out why it returns the value it does.
[Frankly, I'm surprised that f64toint() doesn't short-circuit when funpack64() returns fi = true.]
const mantbits64 uint = 52
const expbits64 uint = 11
const bias64 = -1<<(expbits64-1) + 1
func f64toint(f uint64) (val int64, ok bool) {
fs, fm, fe, fi, fn := funpack64(f)
switch {
case fi, fn: // NaN
return 0, false
case fe < -1: // f < 0.5
return 0, false
case fe > 63: // f >= 2^63
if fs != 0 && fm == 0 { // f == -2^63
return -1 << 63, true
}
if fs != 0 {
return 0, false
}
return 0, false
}
for fe > int(mantbits64) {
fe--
fm <<= 1
}
for fe < int(mantbits64) {
fe++
fm >>= 1
}
val = int64(fm)
if fs != 0 {
val = -val
}
return val, true
}
func funpack64(f uint64) (sign, mant uint64, exp int, inf, nan bool) {
sign = f & (1 << (mantbits64 + expbits64))
mant = f & (1<<mantbits64 - 1)
exp = int(f>>mantbits64) & (1<<expbits64 - 1)
switch exp {
case 1<<expbits64 - 1:
if mant != 0 {
nan = true
return
}
inf = true
return
case 0:
// denormalized
if mant != 0 {
exp += bias64 + 1
for mant < 1<<mantbits64 {
mant <<= 1
exp--
}
}
default:
// add implicit top bit
mant |= 1 << mantbits64
exp += bias64
}
return
}

How can I convert float(-1.0) to int -1 correctly?

my code:
step := 10.0
precision := int(math.Log10(1/step))
fmt.PrintLn(precision)
I want precision == -1 but got 0...
Float to integer conversion truncates, so if your float number is e.g. 0.99, converting it to integer will be 0 and not 1.
If you want to round to an integer, you may simply use math.Round() (which returns float64 so you still need to manually convert to int, but the result will be what you expect):
step := 10.0
precision := int(math.Log10(1 / step))
fmt.Println(precision)
precision = int(math.Round(math.Log10(1 / step)))
fmt.Println(precision)
This will output (try it on the Go Playground):
0
-1
If you want to round to a specific fraction (and not to integer), see Golang Round to Nearest 0.05.

Random number within range and a given granularity in Golang

I've written the following code to create a random number between 0.0 and 10.0.
const minRand = 0
const maxRand = 10
v := minRand + rand.Float64()*(maxRand-minRand)
However, I would like to set the granularity to 0.05, so having all the digits as the least significant decimal should not be allowed, only 0 and 5 should be allowed, e.g.:
the value 7.73 is NOT VALID,
the values 7.7 and 7.75 ARE VALID.
How can I produce such numbers in Go?
You can divide with the granularity, get a pseudo random integer and then multiply with the granularity to scale the result down.
const minRand = 8
const maxRand = 10
v := float64(rand.Intn((maxRand-minRand)/0.05))*0.05 + minRand
fmt.Printf("%.2f\n", v)
This will print:
8.05
8.35
8.35
8.95
8.05
9.90
....
If you don't want to get the same sequence every time rand.Seed(time.Now().UTC().UnixNano()).
From the docs
Seed uses the provided seed value to initialize the default Source to a deterministic state. If Seed is not called, the generator behaves as if seeded by Seed(1). Seed values that have the same remainder when divided by 2^31-1 generate the same pseudo-random sequence. Seed, unlike the Rand.Seed method, is safe for concurrent use.
With lower bounds
const minRand = 0
const maxRand = 10
const stepRand = 0.05
v := float64(rand.Intn((maxRand-minRand)/stepRand))*stepRand + minRand
fmt.Printf("%.2f\n", v)

Convert uint64 to int64 without loss of information

The problem with the following code:
var x uint64 = 18446744073709551615
var y int64 = int64(x)
is that y is -1. Without loss of information, is the only way to convert between these two number types to use an encoder and decoder?
buff bytes.Buffer
Encoder(buff).encode(x)
Decoder(buff).decode(y)
Note, I am not attempting a straight numeric conversion in your typical case. I am more concerned with maintaining the statistical properties of a random number generator.
Your conversion does not lose any information in the conversion. All the bits will be untouched. It is just that:
uint64(18446744073709551615) = 0xFFFFFFFFFFFFFFFF
int64(-1) = 0xFFFFFFFFFFFFFFFF
Try:
var x uint64 = 18446744073709551615 - 3
and you will have y = -4.
For instance: playground
var x uint64 = 18446744073709551615 - 3
var y int64 = int64(x)
fmt.Printf("%b\n", x)
fmt.Printf("%b or %d\n", y, y)
Output:
1111111111111111111111111111111111111111111111111111111111111100
-100 or -4
Seeing -1 would be consistent with a process running as 32bits.
See for instance the Go1.1 release notes (which introduced uint64)
x := ^uint32(0) // x is 0xffffffff
i := int(x) // i is -1 on 32-bit systems, 0xffffffff on 64-bit
fmt.Println(i)
Using fmt.Printf("%b\n", y) can help to see what is going on (see ANisus' answer)
As it turned out, the OP wheaties confirms (in the comments) it was run initially in 32 bits (hence this answer), but then realize 18446744073709551615 is 0xffffffffffffffff (-1) anyway: see ANisusanswer;
The types uint64 and int64 can both represent 2^64 discrete integer values.
The difference between the two is that uint64 holds only positive integers (0 thru 2^64-1), where as int64 holds both negative and positive integers using 1 bit to hold the sign (-2^63 thru 2^63-1).
As others have said, if your generator is producing 0xffffffffffffffff, uint64 will represent this as the raw integer (18,446,744,073,709,551,615) whereas int64 will interpret the two's complement value and return -1.

golang - ceil function like php?

I want to return the least integer value greater than or equal to integer division. So I used math.ceil, but can not get the value I want.
package main
import (
"fmt"
"math"
)
func main() {
var pagesize int = 10
var length int = 43
d := float64(length / pagesize)
page := int(math.Ceil(d))
fmt.Println(page)
// output 4 not 5
}
http://golang.org/pkg/math/#Ceil
http://play.golang.org/p/asHta1HkO_
What is wrong?
Thanks.
The line
d := float64(length / pagesize)
transforms to float the result of the division. Since the division itself is integer division, it results in 4, so d = 4.0 and math.Ceil(d) is 4.
Replace the line with
d := float64(length) / float64(pagesize)
and you'll have d=4.3 and int(math.Ceil(d))=5.
Avoiding floating point operations (for performance and clarity):
x, y := length, pagesize
q := (x + y - 1) / y;
for x >= 0 and y > 0.
Or to avoid overflow of x+y:
q := 1 + (x - 1) / y
It's the same as the C++ version: Fast ceiling of an integer division in C / C++
Convert length and pagesize to floats before the division:
d := float64(length) / float64(pagesize)
http://play.golang.org/p/FKWeIj7of5
You can check the remainder to see if it should be raised to the next integer.
page := length / pagesize
if length % pagesize > 0 {
page++
}

Resources