2017-04-25 476 views

回答

3

無需過分複雜化的事情,當一個簡單的列表解析會爲2的半衰期做

r = 0.5 
a = 1.0 
n = 5 
l = [a*r**i for i in xrange(n)] 

,設置

r = 0.5 ** 0.5 
[1.0, 0.7071067811865476, 0.5000000000000001, 0.35355339059327384, 0.25000000000000006] 
+0

如果我想要2的半衰期,我該如何調整? –

+0

編輯答案 – user3684792

+0

感謝您的澄清! –

0

我得到如下:

import math 
half = 1.0 
decay = math.log(2)/half 
length = 5 

list_d = [math.exp(-decay * i) for i in range(0, length)] 

是不是你要找的?

1

這裏有一種方法使用發電機功能和itertools.islice它做的事:

from itertools import islice 

def halflife(n=1): 
    while True: 
     yield n 
     n /= 2 

print(list(islice(halflife(), None, 5))) 
# [1, 0.5, 0.25, 0.125, 0.0625] 

print(list(islice(halflife(2), None, 5))) 
# [2, 1.0, 0.5, 0.25, 0.125] 
+0

我想我推翻了這個問題,但我仍然沒有看到DV的理由 –

2

嘗試這樣的事情,只能用列表解析

half_life = [0.5**i for i in range(5)] 

輸出=[1.0, 0.5, 0.25, 0.125, 0.0625]

+0

什麼是1 *的?只是'0.5 **我'應該可以正常工作。 –

+0

你說得對,我會編輯它。可能寫得很快。堆棧是競爭:) – Ludisposed

+0

@Ludisposed不,它不是。 – mkrieger1

1
import math 

def decay(start, half_life, length): 
    coef = math.exp(-math.log(2)/half_life) 
    return list(map(lambda t: start * coef ** t, range(length))) 

decay(1, 1, 6) 
# [1.0, 0.5, 0.25, 0.125, 0.0625, 0.03125] 

decay(10, 2, 5) 
# [10.0, 
# 7.0710678118654755, 
# 5.000000000000001, 
# 3.5355339059327386, 
# 2.5000000000000004] 
1
start = 1 
times = 5 
half_life = [start*0.5**i for i in range(times)] 
print (half_life) 

打印:

[1.0, 0.5, 0.25, 0.125, 0.0625] 

,或者如果你不想改變你可以使用一個元組列表,甚至更快:

half_life = tuple(start*0.5**i for i in range(times)) 

打印:

(1.0, 0.5, 0.25, 0.125, 0.0625) 

簡單的程序來演示:

def half_life(start,times): 
    return tuple(start*0.5**i for i in range(times)) 

keep = set('') 
s = input(' Enter start value >') 
s = int(''.join(filter(keep.__contains__, s))) 
t = input(' Enter number of half lives >') 
t = int(''.join(filter(keep.__contains__, t))) 

print (half_life(s,t))