Re: [go-nuts] float exactness

2022-04-11 Thread Sam Hughes
Noting that what @Brian%20Candler just said is bang on, I'll add that if you use `math.Nextafter(y, math.Round(y))` or `y - math.Nextafter(math.Mod(y, 0.01), math.Round(y))`, you can clean up a poorly represented number. The following is Brian's example, but with those two algorithms presented

Re: [go-nuts] float exactness

2022-04-11 Thread Brian Candler
According to the go spec : "Constant expressions are always evaluated exactly; intermediate values and the constants themselves may require precision significantly larger than supported by any predeclared type in the language" Hence there's

Re: [go-nuts] float exactness

2022-04-10 Thread 'wagner riffel' via golang-nuts
On Sat Apr 9, 2022 at 3:56 PM CEST, 'Jack Li' via golang-nuts wrote: > Why literal operation is exact, variable is not? > > fmt.Println(0.1 + 0.2) // 0.3 exactly > fmt.Println(x + y) // 0.30004 > Both aren't exact because floats can't represent 0.3 exactly, they differ because literals

Re: [go-nuts] float exactness

2022-04-09 Thread 'Jack Li' via golang-nuts
Thanks Robert, It is great! a, _ := decimal.NewFromString("0.1") b, _ := decimal.NewFromString("0.2") c := a.Add(b) fmt.Println("decimal:", c) a = decimal.NewFromFloat(0.1) b = decimal.NewFromFloat(0.2) c = a.Add(b) fmt.Println("

Re: [go-nuts] float exactness

2022-04-09 Thread Brian Hatfield
Here's a more general explanation of why floating point operations didn't do what you expected: https://floating-point-gui.de/basic/ On Sat, Apr 9, 2022 at 9:56 AM 'Jack Li' via golang-nuts < golang-nuts@googlegroups.com> wrote: > Hi group, > > 1. > Is there a package can do exact float operation

Re: [go-nuts] float exactness

2022-04-09 Thread Robert Engels
There are several. See github.com/robaho/fixed As to why, read up on numerical analysis. It’s an interesting topic. > On Apr 9, 2022, at 8:56 AM, 'Jack Li' via golang-nuts > wrote: > >  > Hi group, > > 1. > Is there a package can do exact float operations, like Decimal in Python? For >

[go-nuts] float exactness

2022-04-09 Thread 'Jack Li' via golang-nuts
Hi group, 1.  Is there a package can do exact float operations, like Decimal in Python? For example: x := 0.1; y := 0.2; z := x + y; z will be exact 0.3 2. Why literal operation is exact, variable is not? fmt.Println(0.1 + 0.2) // 0.3 exactly fmt.Println(x + y) // 0.30004