why math.Pow gives different results depending on exp type

120 views
Skip to first unread message

DrGo

unread,
Apr 20, 2024, 1:51:21 AM4/20/24
to golang-nuts
```
package main

import (
"fmt"
"math"
)

func main() {
fmt.Printf("%g\n", 1-(math.Pow(0.6, 1/13)))   //result=0
fmt.Printf("%g\n", 1-(math.Pow(0.6, 1.0/13))) // result=0.038532272011602364
}
```

Dan Kortschak

unread,
Apr 20, 2024, 2:05:26 AM4/20/24
to golan...@googlegroups.com
On Fri, 2024-04-19 at 22:51 -0700, DrGo wrote:
> ```
> package main
>
> import (
> "fmt"
> "math"
> )
>
> func main() {
> fmt.Printf("%g\n", 1-(math.Pow(0.6, 1/13)))   //result=0
> fmt.Printf("%g\n", 1-(math.Pow(0.6, 1.0/13))) //
> result=0.038532272011602364
> }
> ```

1/13 is 0 since both parts of the expression are int, and so it
truncates. After this, it is converted to 0.0. So you have 0.6^0 which
is 1.

https://go.dev/play/p/tq2VAPIWXCy

Kurtis Rader

unread,
Apr 20, 2024, 2:07:28 AM4/20/24
to DrGo, golang-nuts
This has nothing to do with the math.Pow function. Dividing two ints (1/13) is not the same as dividing a float by an int (1.0/13). Replace your two `fmt.Printf()` calls with

   println(1 / 13)
   println(1.0 / 13)

and observe the difference. The fact that both `math.Pow` arguments are of type `float64` does not affect the division operator. It only causes the result of the division to be coerced to a `float64` if possible. See https://go.dev/ref/spec#Conversions.

--
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...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/245517a8-37f9-4ad4-bc42-a1204beb723fn%40googlegroups.com.


--
Kurtis Rader
Caretaker of the exceptional canines Junior and Hank

Dominik Honnef

unread,
Apr 20, 2024, 11:46:54 AM4/20/24
to golan...@googlegroups.com
Also, Staticcheck catches this:

$ curl -Os https://go.dev/play/p/oIKGb_uyLb3.go
$ staticcheck oIKGb_uyLb3.go
oIKGb_uyLb3.go:9:38: the integer division '1 / 13' results in zero (SA4025)
Reply all
Reply to author
Forward
0 new messages