●构造一个大小(size)为100(共100 个数)的随机 0、1 数组(array,或称序列),也就是一个只含 0、1 的数组,要求 0 出现的概率为 1/3,1 出现的概率为 2/3,然后打印出该数组,并打印出 0的总个数、1 的总个数。
[提示:可通过构造一个大小为 100 的在[0,1]之间均匀分布的随机数数组结合判断实现]
●再构造一个大小为 10000(共 10000 个数)的正态分布数组(均值为 0,方差为 1 的高斯随机数数组,可用randn 实现),并以0.2 为间隔,统计该数组落入-2~2 范围内的各间隔内的点数(即,统计-2~-1.8,-1.8~-1.6,...,-0.2~0,0~0.2,0.2~0.4,... ,1.8~2 范围内各落入多少个数?),并打印出统计结果(注:应打印出20 个统计结果)、以及这20 个统计结果之和。
import numpy as np
# 随机打印100个数字,1/3概率为0,2/3概率为1
def num_100():
a = np.random.rand(100)
b = list(a)
num_zeros = []
num_ones = []
num = []
for i in b:
if i < 1/3:
num_zeros.append(0)
num.append(0)
else:
num_ones.append(1)
num.append(1)
count_zeros = 0
count_ones = 0
for i in num_zeros:
count_zeros += 1
for i in num_ones:
count_ones += 1
print(count_zeros, num_zeros)
print(count_ones, num_ones)
print(num)
def num_10000():
a = np.random.randn(10000)
b = list(a)
count1 = 0
count2 = 0
count3 = 0
count4 = 0
count5 = 0
count6 = 0
count7 = 0
count8 = 0
count9 = 0
count10 = 0
count11 = 0
count12 = 0
count13 = 0
count14 = 0
count15 = 0
count16 = 0
count17 = 0
count18 = 0
count19 = 0
count20 = 0
for i in b:
if (i >= -2.0 and i < -1.8):
count1 = count1 + 1
if (i >= -1.8 and i < -1.6):
count2 += 1
if (i >= -1.6 and i < -1.4):
count3 += 1
if (i >= -1.4 and i < -1.2):
count4 += 1
if (i >= -1.2 and i < -1.0):
count5 += 1
if (i >= -1.0 and i < -0.8):
count6 +=1
if (i >= -0.8 and i < -0.6):
count7 += 1
if (i >= -0.6 and i < -0.4):
count8 += 1
if (i >= -0.4 and i < -0.2):
count9 += 1
if (i >= -0.2 and i < 0.0):
count10 += 1
if (i >= 0.0 and i < 0.2):
count11 += 1
if (i >= 0.2 and i < 0.4):
count12 += 1
if (i >= 0.4 and i < 0.6):
count13 += 1
if (i >= 0.6 and i < 0.8):
count14 += 1
if (i >= 0.8 and i < 1.0):
count15 += 1
if (i >= 1.0 and i < 1.2):
count16 += 1
if (i >= 1.2 and i < 1.4):
count17 += 1
if (i >= 1.4 and i < 1.6):
count18 += 1
if (i >= 1.6 and i < 1.8):
count19 += 1
if (i >= 1.8 and i <= 2.0):
count20 += 1
sum = count1 + count2 + count3 + count4 + count5 + count6 + count7 + count8 + count9 + count10 + count11 + count12 + count13 + count14 + count15 + count16 + count17 + count18 + count19 + count20
# print(b)
print("-2~2范围内以0.2为间隔,各个间隔内数的个数为:",count1,count2,count3,count4,count5,count6,count7,count8,count9,count10,count11,count12,count13,count14,count15,count16,count17,count18,count19,count20)
print("二十个数据之和为:", sum)
if __name__ == "__main__":
num_100()
num_10000()
# 上述空列表的创建可由下面代码完成
list = [[] for _ in range(20)]
for i in range(20):
print(list[i])
课程上机任务小练习
如有不足 多多指教



