Skip to content

Commit 5f4e276

Browse files
authored
Merge pull request #673 from devlights:add-wrong-floating-point-calc-example
Add floatop/rounding_error.go
2 parents fad4ace + 9638dec commit 5f4e276

File tree

3 files changed

+43
-1
lines changed

3 files changed

+43
-1
lines changed

examples/basic/floatop/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,4 @@
55
|file|example name|note|
66
|----|------------|----|
77
|order\_of\_computation.go|floatop\_order\_of\_computation|浮動小数点は計算の順序によって結果が変わることのサンプルです|
8-
8+
|rounding\_error.go|floatop\_rounding\_error|小数点計算において近似値が利用され丸め誤差が出るサンプルです|

examples/basic/floatop/examples.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,5 @@ func NewRegister() mapping.Register {
1414
// Regist -- 登録します.
1515
func (r *register) Regist(m mapping.ExampleMapping) {
1616
m["floatop_order_of_computation"] = OrderOfComputation
17+
m["floatop_rounding_error"] = RoundingError
1718
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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+
}

0 commit comments

Comments
 (0)