File tree Expand file tree Collapse file tree 3 files changed +43
-1
lines changed Expand file tree Collapse file tree 3 files changed +43
-1
lines changed Original file line number Diff line number Diff line change 5
5
| file| example name| note|
6
6
| ----| ------------| ----|
7
7
| order\_ of\_ computation.go| floatop\_ order\_ of\_ computation| 浮動小数点は計算の順序によって結果が変わることのサンプルです|
8
-
8
+ | rounding \_ error.go | floatop \_ rounding \_ error | 小数点計算において近似値が利用され丸め誤差が出るサンプルです |
Original file line number Diff line number Diff line change @@ -14,4 +14,5 @@ func NewRegister() mapping.Register {
14
14
// Regist -- 登録します.
15
15
func (r * register ) Regist (m mapping.ExampleMapping ) {
16
16
m ["floatop_order_of_computation" ] = OrderOfComputation
17
+ m ["floatop_rounding_error" ] = RoundingError
17
18
}
Original file line number Diff line number Diff line change
1
+ package floatop
2
+
3
+ import (
4
+ "math/big"
5
+
6
+ "github.com/devlights/gomy/output"
7
+ )
8
+
9
+ // RoundingError は、小数点計算において近似値が利用され丸め誤差が出るサンプルです。
10
+ //
11
+ // # REFERENCES
12
+ // - https://engineering.mercari.com/blog/entry/20201203-basis-point/
13
+ func RoundingError () error {
14
+ //
15
+ // 0.01は2進数で正確に表現できないため、近似値が利用されて丸め誤差が生じる
16
+ //
17
+ var (
18
+ v float64
19
+ )
20
+
21
+ for i := 0 ; i < 1000 ; i ++ {
22
+ v += 0.01
23
+ }
24
+
25
+ output .Stdoutl ("[float64]" , v ) // 9.999999999999831
26
+
27
+ //
28
+ // math/big を利用して同様の処理を行う
29
+ //
30
+ var (
31
+ v2 = new (big.Rat )
32
+ )
33
+
34
+ for i := 0 ; i < 1000 ; i ++ {
35
+ v2 = new (big.Rat ).Add (v2 , big .NewRat (1 , 100 ))
36
+ }
37
+
38
+ output .Stdoutl ("[big.Rat]" , v2 .FloatString (1 )) // 10.0
39
+
40
+ return nil
41
+ }
You can’t perform that action at this time.
0 commit comments