基于小时的概率运行

时间:2016-10-07 16:12:04

标签: python

我有一个函数,我希望每小时运行的概率越来越高,直到正午,然后将概率降低到午夜。我可以想象一个以正午为中心的正态分布会这样做(所以运行函数的概率在正午时为100%但在午夜时非常低),但我无法将其转换为python代码。

例如,如果代码在凌晨1点执行,则运行概率非常低。但如果代码在中午执行,则它有100%的运行概率。

这是一个完全粗暴,单一的,手工尝试我想要的东西:

currentHour = 12

if currentHour == 1:
    print('probability = 0')
elif currentHour == 2:
    print('probability = 0')
elif currentHour == 3:
    print('probability = .1')
elif currentHour == 4:
    print('probability = .2')
elif currentHour == 5:
    print('probability = .3')
elif currentHour == 6:
    print('probability = .4')
elif currentHour == 7:
    print('probability = .5')
elif currentHour == 8:
    print('probability = .6')
elif currentHour == 9:
    print('probability = .7')
elif currentHour == 10:
    print('probability = .8')
elif currentHour == 11:
    print('probability = .9')
elif currentHour == 12:
    print('probability = 1')
elif currentHour == 13:
    print('probability = .9')
elif currentHour == 13:
    print('probability = .8')
elif currentHour == 14:
    print('probability = .7')
elif currentHour == 15:
    print('probability = .6')
elif currentHour == 16:
    print('probability = .5')
elif currentHour == 17:
    print('probability = .4')
elif currentHour == 18:
    print('probability = .3')
elif currentHour == 19:
    print('probability = .2')
elif currentHour == 20:
    print('probability = .1')
elif currentHour == 21:
    print('probability = 0')
elif currentHour == 22:
    print('probability = 0')
elif currentHour == 23:
    print('probability = 0')
elif currentHour == 24:
    print('probability = 0')

2 个答案:

答案 0 :(得分:1)

纯粹的魔法。我想到了。不,只是在开玩笑。当你问这个问题时,它立刻让我想起了窦波,它们再次上升然后再下降 - 就像你想要做的那样。

根据this页面:

  

由y = sin x定义的函数图称为正弦波或正弦波。 [...]此图重复每6.28单位或2 pi弧度。范围从-1到1.

所以我想出了这个:

sin((hour/24)*pi)

你可以像这样在python中集成它:

import math
import time
hour = int(time.strftime("%H"))
probability = math.sin(hour/24.0*math.pi)
print(probability)

为什么呢?因为sin(0*pi)是0而sin(0.5*pi)1。你希望在12小时时概率最高,所以1。该值出现在sin(0.5*pi)上。 24小时后,该值将为sin(1*pi),再次为0

然后我将该值从0转换为1,转换为024,将当前小时除以24

Half sine

答案 1 :(得分:1)

很多选择。只需创建一个函数,该函数根据小时返回0到1之间的值。然后,在0和1之间进行随机浮动。如果浮点数小于概率,则运行程序。

import numpy as np

def prob_sawtooth(hour):
    return 1. - abs((hour - 12.) / 12.)

def prob_sin(hour):
    return np.sin(hour / 24. * np.pi)

def prob_gaussian(hour, stdev=6.):
    gauss = lambda x, m, s: np.exp(-(x-m)**2 / (2*s**2)) / np.sqrt(2*np.pi*s**2)
    return gauss(hour, 12., stdev) / gauss(12., 12., stdev)

test = np.random.rand()
#14:00
if test <= prob_gaussian(14.):
    # run program
    pass