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 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.30000000000000004
>
>
> Thanks
>
>
> func main() {
> x := 0.1
> y := 0.2
> fmt.Println("x + y  :", x   + y)
> fmt.Println("literal:", 0.1 + 0.2)
>
> x = 0.1
> y = 0.35
> fmt.Println("x + y  :", x   + y)
> fmt.Println("literal:", 0.1 + 0.35)
> }
>
> /*
> $ go build && ./main
> x + y  : 0.30000000000000004
> literal: 0.3
> x + y  : 0.44999999999999996
> literal: 0.45
> $
> */
>
>
> // Python:
>
> // >>> 0.1 + 0.2
> // 0.30000000000000004
>
> // >>> float(Decimal('0.1') + Decimal('0.2'))
> // 0.3
> // >>>
>
> // >>> 0.35 + 0.1
> // 0.44999999999999996
>
> // >>> float(Decimal('0.35') + Decimal('0.1'))
> // 0.45
> // >>>
>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/tencent_327903B1334351F91FC17D18F2C6E1937508%40qq.com
> <https://groups.google.com/d/msgid/golang-nuts/tencent_327903B1334351F91FC17D18F2C6E1937508%40qq.com?utm_medium=email&utm_source=footer>
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CANGiwgbAGa9fsweTCsJ11WJkuQH7U-qhafjc85442nTzLTzqNQ%40mail.gmail.com.

Reply via email to