这是我用来评估y =(exp ^( - mu)* mu ** N)/(n!)0< = n< = N:
的当前python代码N = 10
mu = 2
n = np.arange(0, N+1)
numerator = (np.exp(-mu)) * mu**n
denominator = factorial(n)
function = numerator / denominator
print('N =', str(N), 'mu =', str(mu))
print('n = {:}'.format(n))
print('function = {:}'.format(function))
我得到的当前输出是:
N = 10 mu = 2
n = [ 0 1 2 3 4 5 6 7 8 9 10]
function = [ 1.35335283e-01 2.70670566e-01 2.70670566e-01 1.80447044e-
01
9.02235222e-02 3.60894089e-02 1.20298030e-02 3.43708656e-03
8.59271640e-04 1.90949253e-04 3.81898506e-05]
我想要的是输出是列表,而不是数组。对于n的每个值,我想要函数的相应值。即:
N = 10 mu = 2
n = 0, function = 1.35335283e-01
n = 1, function = 2.70670566e-01
...
n = 10, function = 3.81898506e-05
我尝试过其他方法,其中大多数都导致了以下TypeError:
print('n = {:.}'.format(n))
TypeError: non-empty format string passed to object.__format__
我已设法使用' for'循环,但我想在循环之外做一个这样的方法,因为我试图在不使用任何循环的情况下进行大学练习。 有谁知道怎么做?
答案 0 :(得分:1)
您可以将输出压缩在一起,但是您需要填充n并使用循环功能。为什么要串?
n = [0,1,2,3,4,5,6,7,8,9,10]
function = [1.35335283e-01,2.70670566e-01,2.70670566e-01,
1.80447044e-01,9.02235222e-02,3.60894089e-02,
1.20298030e-02,3.43708656e-03,8.59271640e-04,
1.90949253e-04,3.81898506e-05]
zipped = list(zip(n,function))
zipped
Out[ ]:
[(0, 0.135335283),
(1, 0.270670566),
(2, 0.270670566),
(3, 0.180447044),
(4, 0.0902235222),
(5, 0.0360894089),
(6, 0.012029803),
(7, 0.00343708656),
(8, 0.00085927164),
(9, 0.000190949253),
(10, 3.81898506e-05)]
我同意不允许你用循环打印是一个毫无意义的要求。
for a,b in zipped:
print('n =',a,', function =',b)
Out[ ]:
n = 0 , function = 0.135335283
n = 1 , function = 0.270670566
n = 2 , function = 0.270670566
n = 3 , function = 0.180447044
n = 4 , function = 0.0902235222
n = 5 , function = 0.0360894089
n = 6 , function = 0.012029803
n = 7 , function = 0.00343708656
n = 8 , function = 0.00085927164
n = 9 , function = 0.000190949253
n = 10 , function = 3.81898506e-05
答案 1 :(得分:0)
您可以通过以下方式使用numpy.vectorize
import numpy as np
def custom_print(n, f):
print("n = {}, function = {}".format(n, f))
vprint = np.vectorize(custom_print)
n = np.array([1, 2, 3])
f = np.array([1, 4, 9])
vprint(n, f)
输出
n = 1, function = 1
n = 2, function = 4
n = 3, function = 9
正如FHTMitchell在评论中所述
提供
vectorize
功能主要是为了方便,而不是为了提高性能。实现基本上是for循环。
(来自docpage:https://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html)