This question already has an answer here:
How to perform division in Go
(1 answer)
Closed 1 year ago.
Why doesn't my float64 have any decimal points?
I expected 40000/3 should return something like 13333.3333
package main
import (
"fmt"
)
func main() {
var f float64 = 40000 / 3
fmt.Println(f)
}
https://play.golang.org/p/OxjLjwPGYhx
40000/3 is an integer value. It is then converted to a float. To perform float division use float values. 40000.0/3 will result in a float value.
Related
I am new to Go and currently following A Tour of Go.
I am currently at page Numeric Constants. Down below is a trimmed down version of the code that runs on that page:
package main
import "fmt"
const Big = 1 << 100
func needFloat(x float64) float64 {
return x * 0.1
}
func main() {
fmt.Println(needFloat(Big))
// fmt.Printf("Type of Big %T", Big)
}
this code compiles successfully with the output 1.2676506002282295e+29
The following code however will not compile and give an error:
package main
import "fmt"
const Big = 1 << 100
func needFloat(x float64) float64 {
return x * 0.1
}
func main() {
fmt.Println(needFloat(Big))
fmt.Printf("Type of Big %T", Big)
}
Output:
./prog.go:9:13: constant 1267650600228229401496703205376 overflows int
Why do you think this happened? I hope you will kindly explain.
The constant Big is an untyped constant. An untyped constant can be arbitrarily large and it doesn't have to fit into any predefined type's limits. It is interpreted and truncated in the context it is used.
The function needFloat gets a float64 argument. At this instance Big is converted to a float64 and used that way.
When you use it for Printf, it tries to pass it in as an int because it is not a decimal number (otherwise it would've converted it to float64), and it causes an overflow. Pass it as float64(Big), and it should work.
I guess the reason is that Big gets computed (i.e. casted right before being passed to needFloat, and gets instead computed as a int64 before the Printf. As a proof, the following statement computes correctly:
package main
import "fmt"
const Big = 1 << 100
func main() {
fmt.Printf("Type of Big %T", float64(Big))
}
Hope this helps.
The untyped constant n must be converted to a type before it can be assigned to the interface{} parameter in the call to fmt.Println.
fmt.Println(a ...interface{})
When the type can’t be inferred from the context, an untyped constant is converted to a bool, int, float64, complex128, string or rune depending of the format of the constant.
In this case the constant is an integer, but n is larger than the maximum value of an int.
However, n can be represented as a float64.
const n = 9876543210 * 9876543210
fmt.Println(float64(n))
For exact representation of big numbers, the math/big package implements arbitrary-precision arithmetic. It supports signed integers, rational numbers and floating-point numbers.
This is taken from https://yourbasic.org/golang/gotcha-constant-overflows-int/.
This question already has an answer here:
Golang Round to Nearest 0.05
(1 answer)
Closed 4 years ago.
I want to trim latitude and longitude of address upto 5 decimal points.
latitude and longitude are of type float64 I have created a function round the value.
My function is like this::
func DoubleRoundFive(val float64) float64 {
formattedVal := fmt.Sprintf("%.5f", val)
roundedVal, _ := strconv.ParseFloat(formattedVal, 64)
return roundedVal
}
Output and usage::
DoubleRoundFive(76.70289609999999)
Output::
76.7029
But I just want to trim the value upto 5 decimal points. I want output as 76.70289 . Is it possible in GO??
I want exact 5 decimal values because I am using this for latitude longitude.
This is a GO playground Link
Try this:
package main
import (
"fmt"
)
func main() {
val := DoubleRoundFive(76.70289609999999)
fmt.Println(val)
}
func DoubleRoundFive(val float64) float64 {
valInt := int64(val*100000)
val = float64(valInt)/100000
return val
}
Go Playground: https://play.golang.org/p/O_H_buvJtDO
The math.Floor in Golang returns a float64. But I would like it to return an integer. How can I get the integer value after performing the floor operation? Can I just use int(x) or int32(x) or int64(x)? I worry that the integer range might not match that of a float64 result therefore brings inaccuracy to the operation.
You may just want to check beforehand; if the conversion will perform safely or an overflow will occur.
As John Weldon suggested,
package main
import (
"fmt"
"math"
)
func main() {
var (
a int64
f64 float64
)
// This number doesn't exist in the float64 world,
// just a number to perform the test.
f64 = math.Floor(9223372036854775808.5)
if f64 >= math.MaxInt64 || f64 <= math.MinInt64 {
fmt.Println("f64 is out of int64 range.")
return
}
a = int64(f64)
fmt.Println(a)
}
Go Playground
I hope this will answer your question.
Also, I'd really like to know if any better solution is available. :)
You can compare the float64 value with math.MaxInt64 or math.MinInt64 before doing the conversion.
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
Consider the following code written in go:
package main
import "fmt"
func main() {
const pi float64 = 22 / 7
fmt.Println("pi value", pi)
}
here the value of pi is 3. The question is why is the value losing precision even though it is of type float64?
NeverMind, I got the answer.
package main
import "fmt"
func main() {
const pi float64 = 22.0 / 7.0
fmt.Println("pi value", pi)
}
Output 3.142857142857143. it seems types depend if type integer are be divided, it will return a integer regardless if the receiving var is type float64. so get a float value, devision has you occur between float values.