From 4f013f593eaba1cff4f39d5e8cb091473f0acfd4 Mon Sep 17 00:00:00 2001 From: kercylan98 Date: Sat, 20 May 2023 11:42:49 +0800 Subject: [PATCH] =?UTF-8?q?=E8=BE=85=E5=8A=A9=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/maths/math.go | 49 ++++++++++++++++++++++++++++++++++++++++++ utils/network/float.go | 17 +++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 utils/maths/math.go create mode 100644 utils/network/float.go diff --git a/utils/maths/math.go b/utils/maths/math.go new file mode 100644 index 0000000..ac9ec39 --- /dev/null +++ b/utils/maths/math.go @@ -0,0 +1,49 @@ +package maths + +// Pow 整数幂运算 +func Pow(a, n int) int { + if a == 0 { + return 0 + } + if n == 0 { + return 1 + } + if n == 1 { + return a + } + var result int = 1 + factor := a + for n != 0 { + if n&1 != 0 { + // 当前位是 1,需要乘进去 + result *= factor + } + factor *= factor + n = n >> 1 + } + return result +} + +// PowInt64 整数幂运算 +func PowInt64(a, n int64) int64 { + if a == 0 { + return 0 + } + if n == 0 { + return 1 + } + if n == 1 { + return a + } + var result int64 = 1 + factor := a + for n != 0 { + if n&1 != 0 { + // 当前位是 1,需要乘进去 + result *= factor + } + factor *= factor + n = n >> 1 + } + return result +} diff --git a/utils/network/float.go b/utils/network/float.go new file mode 100644 index 0000000..9226a92 --- /dev/null +++ b/utils/network/float.go @@ -0,0 +1,17 @@ +package network + +import ( + "fmt" + "github.com/kercylan98/minotaur/utils/generic" + "github.com/kercylan98/minotaur/utils/maths" + "strings" +) + +// FloatEnlarge 用于将浮点型放大后进行网络传输,返回放大后的值和放大的倍率 +// - 存在精度丢失问题,如1.13 +func FloatEnlarge[F generic.Float](f F) (value int64, multi int64) { + str := fmt.Sprint(f) + multi = maths.PowInt64(10, int64(len(str[strings.Index(str, ".")+1:]))) + value = int64(f * F(multi)) + return +}