Created
September 24, 2016 01:35
-
-
Save fengxsong/b7e4ed656860c632974aa7886c8c9d72 to your computer and use it in GitHub Desktop.
将total块钱随机分给num个人,最大值maxVal,最小值minVal。float64的精度问题?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"strconv" | |
"time" | |
) | |
type RandMoney struct { | |
num int | |
total, minVal, maxVal float64 | |
} | |
func (r *RandMoney) tmpArr() []int { | |
min := int(r.minVal * 100) | |
max := int(r.maxVal * 100) | |
if min == 0 { | |
min += 1 | |
} | |
initMin := min | |
initMax := max | |
total := int(r.total * 100) | |
arr := make([]int, r.num) | |
cInt := make(chan int) | |
defer close(cInt) | |
go func() { | |
for i := 0; i < r.num; i++ { | |
time.Sleep(1 * time.Nanosecond) | |
cInt <- randRange(min, max) | |
} | |
}() | |
for i := 0; i < r.num; i++ { | |
rnd := <-cInt | |
arr[i] = rnd | |
total -= rnd | |
} | |
for { | |
if total == 0 { | |
return arr | |
} | |
pos := randRange(0, r.num) | |
if total > 0 { | |
if arr[pos]+1 <= int(initMax) { | |
arr[pos] += 1 | |
total -= 1 | |
} | |
} else { | |
if arr[pos]-1 >= int(initMin) { | |
arr[pos] -= 1 | |
total += 1 | |
} | |
} | |
} | |
} | |
func (r *RandMoney) float64Arr() []float64 { | |
tmparr := r.tmpArr() | |
arr := make([]float64, r.num) | |
// var tmpT float64 | |
for i := 0; i < r.num; i++ { | |
tmpf := fmt.Sprintf("%.2f", float64(tmparr[i])/100) | |
f, _ := strconv.ParseFloat(tmpf, 10) | |
// tmpT += f | |
arr[i] = f | |
} | |
// arr[r.num-1] = r.total - tmpT | |
return arr | |
} | |
func randRange(min, max int) int { | |
rand.Seed(time.Now().UnixNano()) | |
return rand.Intn(max-min) + min | |
} | |
func main() { | |
r := RandMoney{ | |
num: 100, | |
total: 50, | |
minVal: 0, | |
maxVal: 10, | |
} | |
start := time.Now() | |
arr := r.float64Arr() | |
fmt.Println("generate array tooks ", time.Now().Sub(start)) | |
var t float64 | |
for _, f := range arr { | |
t += f | |
} | |
fmt.Println(arr) | |
fmt.Println("sum float64: ", int(t)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment