1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Go の、型のない定数の精度

Last updated at Posted at 2018-03-13

Go の定数には型のないものがあり

型のない定数を基本型の値よりも遥かに高い数値精度で表現します
( 『プログラミング言語Go』 p88 )

ということになっている。
じゃあどんだけなんだ、ということで、試してみた。

ruby
S=%Q!package main

import (
	"fmt"
)

const(
  a = 1
  b = 0.%s
  c=(a-b)*1%s
)

func main() {
  fmt.Printf( "%%.18f", c )
}!

def test(n)
  code = S % [ "9"*n, "0"*n ]
  File.open( "hoge.go", "w" ){ |f| f.puts(code) }
  %x( go run hoge.go )
end

(1..1000).each do |n|
  p [ n, r=test(n) ]
  break if r.to_f.round!=1
end

こんなコードを実行してみたら:

[1, "1.000000000000000000"]
[2, "1.000000000000000000"]
[3, "1.000000000000000000"]
«中略»
[138, "1.000000000000000000"]
[139, "1.000000000000000222"]
[140, "1.000000000000000222"]
[141, "1.000000000000029976"]
[142, "0.999999999999806266"]
[143, "0.999999999996822986"]
[144, "1.000000000004281242"]
[145, "1.000000000004281242"]
[146, "0.999999997766779058"]
[147, "1.000000005225119892"]
[148, "1.000000154391934348"]
[149, "0.999999408557861291"]
[150, "1.000014325239323654"]
[151, "1.000163492053947722"]
[152, "0.999417657980827712"]
[153, "0.969584295056026835"]
[154, "0.745834073120020702"]
# command-line-arguments
./hoge.go:10:11: constant too large: 100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

こんな結果になった。

上記の例だと、10進数で 138桁 ≒ 2進数で458桁 ぐらいまで誤差がみえない。
458 + 53(float64の仮数部) = 511。

で、10進数で 154桁≒2進数で514桁 で死んだ。
たぶん内部表現は 512bit なんだと思う。

ちなみに go は、「go version go1.10 darwin/amd64」です。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?