diff options
| author | Adrien Hopkins <adrien.p.hopkins@gmail.com> | 2023-08-25 10:40:00 -0500 |
|---|---|---|
| committer | Adrien Hopkins <adrien.p.hopkins@gmail.com> | 2023-08-25 10:46:59 -0500 |
| commit | b9164fb5b41136a63391f5675a848ec4a7711cb6 (patch) | |
| tree | 6aa7f00fb2e53462f7cb64ff0a0e56bc8f8b6e59 | |
| parent | 99c4b2d9980dd14e8c43ffbf00660047335ada4b (diff) | |
Make totative ratio exact
(or, as exact as possible within a float64 - I only do one float
division, and everything else is a uint, so I think this means I will
get the closest available float64 value every time)
| -rw-r--r-- | factors/factors_test.go | 19 | ||||
| -rw-r--r-- | factors/totative.go | 7 |
2 files changed, 9 insertions, 17 deletions
diff --git a/factors/factors_test.go b/factors/factors_test.go index 33727c0..b7f48b9 100644 --- a/factors/factors_test.go +++ b/factors/factors_test.go @@ -3,7 +3,6 @@ package factors import ( "fmt" "maps" - "math" "testing" ) @@ -59,18 +58,14 @@ func TestFactors(t *testing.T) { } var totativeRatioCases = map[uint]float64{ - 1: 1.0, - 2: 0.5, - 3: 2.0 / 3.0, - 4: 0.5, - 6: 1.0 / 3.0, - 8: 0.5, - 12: 1.0 / 3.0, + 1: 1.0, 2: 0.5, 3: 2.0 / 3.0, 4: 0.5, + 6: 1.0 / 3.0, 7: 6.0 / 7.0, 8: 0.5, + 12: 1.0 / 3.0, 14: 3.0 / 7.0, 15: 8.0 / 15.0, + 30: 4.0 / 15.0, 60: 4.0 / 15.0, 120: 4.0 / 15.0, } func TestTotativeRatio(t *testing.T) { - equals := func(a, b float64) bool { return floatEquals(a, b, 1e-15) } - tableTest(t, TotativeRatio, totativeRatioCases, equals, "TotativeRatio") + tableTest(t, TotativeRatio, totativeRatioCases, stdEquals, "TotativeRatio") } var factorScoreCases = map[uint]float64{ @@ -199,7 +194,3 @@ func setEquals[E comparable](a, b []E) bool { } return maps.Equal(aSet, bSet) } - -func floatEquals(a, b, maxDelta float64) bool { - return math.Abs(a-b) <= maxDelta*math.Max(math.Abs(a), math.Abs(b)) -} diff --git a/factors/totative.go b/factors/totative.go index 558f0f0..3a1f635 100644 --- a/factors/totative.go +++ b/factors/totative.go @@ -8,10 +8,11 @@ func TotativeRatio(n uint) float64 { } primeFactorization := PrimeFactorize(n) + num, denom := uint(1), uint(1) - totativeRatio := 1.0 for p := range primeFactorization.exponents { - totativeRatio *= float64(p - 1) / float64(p) + num *= p - 1 + denom *= p } - return totativeRatio + return float64(num) / float64(denom) } |
