GO lang - constant truncated integer

The following GO program gives an error:

./fft.go:13: constant -6.28319 truncated to integer ./fft.go:13: cannot use -7 * k / N (type int) as type float64 in assignment 

Program:

 package main import ( "math" "fmt" ) func main() { fmt.Println("Hello world ",math.E) var k, N int = 1, 10 var ans float64 = 0 var c float64 = (-2.0 * math.Pi * k) / N x := make([]float64,N) for i := 0; i < len(x); i++ { x[i] = 1 } ans = 0 for i := 0; i < N; i++ { ans += x[i] * math.E } fmt.Println(ans) } 

Why am I not using int in float64 type?

+6
source share
1 answer

Replace

 var c float64 = (-2.0 * math.Pi * k) / N 

by

 var c float64 = (-2.0 * math.Pi * float64(k)) / float64(N) 

To quote spec :

Conversions are required when different numeric types are mixed into expressions or assignments. For example, int32 and int do not match the type, even if they can be the same size for a particular architecture.

Go uses static typing and does not automatically convert numeric types. The reason is probably to avoid some errors. For example, what value and what type should float64(2.5) * int(2) give? Should the result be int(5) ? int(4) ? float64(5.0) ? Go is not a problem. The Go Go FAQ has more to say about this.


@jnml indicates that in this case is enough:

 var c float64 = -2 * math.Pi / float64(N) 
+10
source

All Articles