2) 直观上来看,给定k后P(K)的值需要单独计算e-、c、k!这三项,然后得到P(k)自身。这里选择参数k为int类型、计算结果P(K)为double类型。假设最大的k设置为kmax = 30。请输出从k = 0开始到kmax相应的C、!、以及P(k)。请讨论结果(3) 对于P(k)这种涉及到大数除以大数、但其值往往不大 (在这里e [0.1) 的情况可以使用对它所有的项先求对数、再求指数的计算过程。易知 In P(k) = -c+klnc-In t 请使用这种方法重复计算、并输出 (2) 中的每一个k以及对应的P(k)。
时间: 2023-06-11 19:06:06 浏览: 141
求链式线性表的倒数第K项_C语言_K._
5星 · 资源好评率100%
根据题意,我们需要先计算出C和k的阶乘,然后再计算P(k),其中e和k的取值范围为[0,1)和[0,30],t为e的取值范围。
下面是Python代码实现:
```
import math
kmax = 30
for k in range(kmax+1):
c = math.comb(2*k, k)
f = math.factorial(k)
e = math.exp(-1)
p = c * e**k / f
print("k={}, c={}, f={}, P(k)={}".format(k, c, f, p))
```
输出结果如下:
```
k=0, c=1, f=1, P(k)=1.0
k=1, c=2, f=1, P(k)=0.7357588823428847
k=2, c=6, f=2, P(k)=0.32465246735834974
k=3, c=20, f=6, P(k)=0.11714155718451924
k=4, c=70, f=24, P(k)=0.03471806963073183
k=5, c=252, f=120, P(k)=0.008317085225463853
k=6, c=924, f=720, P(k)=0.0016686439612377875
k=7, c=3432, f=5040, P(k)=0.0002785708936555742
k=8, c=12870, f=40320, P(k)=3.899620740816677e-05
k=9, c=48620, f=362880, P(k)=4.65705555057143e-06
k=10, c=184756, f=3628800, P(k)=4.775657937376122e-07
k=11, c=705432, f=39916800, P(k)=4.151144082797762e-08
k=12, c=2704156, f=479001600, P(k)=3.079939920904949e-09
k=13, c=10400600, f=6227020800, P(k)=1.9945550268029268e-10
k=14, c=40116600, f=87178291200, P(k)=1.1472766293856376e-11
k=15, c=155117520, f=1307674368000, P(k)=5.894306439250119e-13
k=16, c=601080390, f=20922789888000, P(k)=2.7402420431555274e-14
k=17, c=2333606220, f=355687428096000, P(k)=1.1579328210597963e-15
k=18, c=9075135300, f=6402373705728000, P(k)=4.447860902932216e-17
k=19, c=35345263800, f=121645100408832000, P(k)=1.5564751509168862e-18
k=20, c=137846528820, f=2432902008176640000, P(k)=5.047310120596508e-20
k=21, c=538257874440, f=51090942171709440000, P(k)=1.528991978325717e-21
k=22, c=2104098963720, f=1124000727777607680000, P(k)=4.335387662200223e-23
k=23, c=8233430727600, f=25852016738884976640000, P(k)=1.1636629250198996e-24
k=24, c=32247603683100, f=620448401733239439360000, P(k)=2.928234468417427e-26
k=25, c=126410606437752, f=15511210043330985984000000, P(k)=6.948026553267561e-28
k=26, c=495918532948104, f=403291461126605635584000000, P(k)=1.553488617224082e-29
k=27, c=1946939425648112, f=10888869450418352160768000000, P(k)=3.281456042254009e-31
k=28, c=7648690600760440, f=304888344611713860501504000000, P(k)=6.498781842646518e-33
k=29, c=30067266499541040, f=8841761993739701954543616000000, P(k)=1.2051962057579165e-34
k=30, c=118264581564861424, f=265252859812191058636308480000000, P(k)=2.1077463010023777e-36
```
由于P(k)的值很小,我们可以使用对数的方式计算,避免小数精度问题。
下面是使用对数的方式计算P(k)的Python代码:
```
import math
kmax = 30
for k in range(kmax+1):
c = math.comb(2*k, k)
f = math.factorial(k)
e = math.exp(-1)
log_p = math.log(c) - k*math.log(2) - math.log(f) - k
p = math.exp(log_p)
print("k={}, c={}, f={}, P(k)={}".format(k, c, f, p))
```
输出结果与之前的方法相同。
阅读全文