-
Notifications
You must be signed in to change notification settings - Fork 0
/
diophantine.go
51 lines (43 loc) · 1.3 KB
/
diophantine.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Copyright (c) 2022 Teal.Finance contributors
// This file is part of Diophantine under the MIT License.
// SPDX-License-Identifier: MIT
// Package diophantine approximates a real number by a fraction of two rational numbers,
// also known as rational approximation, fraction approximation or ratio approximation.
// This is not about reducing fraction (irreducible fraction).
// See https://wikiless.org/wiki/Diophantine_approximation
package diophantine
import (
"math"
"github.com/bodokaiser/approx"
"github.com/pnelson/fraction"
)
type Fraction struct {
// Num and Den are the numerator and denominator
Num, Den int
}
func Approximate(x float64) []Fraction {
var out []Fraction
for den := math.MaxInt32; den > 9; den-- {
var num int
num, den = approxRatioConstr(x, den)
out = append(out, Fraction{num, den})
}
return out
}
func ApproximatePhil(x float64) []Fraction {
var out []Fraction
for den := math.MaxInt32; den > 9; den-- {
var num int
num, den = fractionFraction(x, den)
out = append(out, Fraction{num, den})
}
return out
}
func approxRatioConstr(x float64, maxDen int) (int, int) {
n, d := approx.RatioConstr(x, uint(maxDen))
return int(n), int(d)
}
func fractionFraction(x float64, maxDen int) (int, int) {
n, d, _ := fraction.Fraction(x, int64(maxDen))
return int(n), int(d)
}