美文网首页
2019-03-17-一周总结+ random rounding

2019-03-17-一周总结+ random rounding

作者: 生病喝药水 | 来源:发表于2019-03-17 23:08 被阅读0次

上周把看过的论文整理一下。总结心得基本写在“I CAN DO IT”系列。
周六看花
周天看了random rounding 代码

import random
import math
import numpy as np

def prob_round(x):
    sign = np.sign(x)
    x = abs(x)   #取正
    is_up = random.random() < x-int(x)   #random.random() 在[0,1)中生成一个随机数, is_up为false or true
    round_func = math.ceil if is_up else math.floor  # if true ->执行math.ceil(0.6->1) else 执行math.floor(0.6->0)
    return sign * round_func(x)

x = 6.1
sum( prob_round(x) for i in range(100) ) / 100.
=> 6.12
EDIT: adding an optional prec argument:

def prob_round(x, prec = 0):
    fixup = np.sign(x) * 10**prec
    x *= fixup
    is_up = random.random() < x-int(x)
    round_func = math.ceil if is_up else math.floor
    return round_func(x) / fixup

x = 8.33333333
[ prob_round(x, prec = 2) for i in range(10) ] #prec值代表 rounding 到小数点prec位
=> [8.3399999999999999,
 8.3300000000000001,
 8.3399999999999999,
 8.3300000000000001,
 8.3300000000000001,
 8.3300000000000001,
 8.3300000000000001,
 8.3300000000000001,
 8.3399999999999999,
 8.3399999999999999]
 

其中,
sign(x):
=1 if x>0
=-1 if x<0
=0 if x=0

相关文章

网友评论

      本文标题:2019-03-17-一周总结+ random rounding

      本文链接:https://www.haomeiwen.com/subject/yrapmqtx.html