You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.5 KiB

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# python
曲线为y=sinx/x+1在[0, 10π]区间上的图像要求定积分∫_0^10π▒(sinx/x+1)。
import numpy as np
def MCint(f, a, b, n, fmin,fmax):
x = np.random.uniform(a, b, n)
y = np.random.uniform(fmin, fmax, n)
cnt = y[ (y>0) & (y < f(x))].size #横轴上方部分
cnt-= y[ (y<0) & (y > f(x))].size #横轴下方积分为负数
area = cnt/n*(b-a)*(fmax-fmin)
return area
print(MCint(lambda x:np.sin(x)/x + 1, 0,10*np.pi, 1000000, 0,2))
输出结果32.94902375084975
import numpy as np
data1 = [6, 7.5, 8, 0, 1]
arr1 = np.array( data1)
print(arr1)
输出:
[ 6. , 7.5, 8. , 0. , 1. ]
shape指出数组的形状shape是个元组
ndim指出数组的维度
dtype指出数组中的元素的类型
reshape函数可以改变数组的维度
astype 函数可生成一个新的数组并指定新的dtype
import numpy as np
data1 = [[6, 7.5, 8, 0, 1], [3.2, 3, 7, 52, 23.4]]
arr1 = np. array( data1)
print(arr1.shape, arr1.ndim, arr1.dtype)
输出:
(2, 5) 2 float64
import numpy as np
arr1 = np.array([1,2,3,4,5,6]) #6个元素的一维数组
arr1 = arr1.reshape(2,3) #改变为2行3列的二维数组
print(arr1)
arr2 = arr1.astype(str)
print(arr2)
输出:
[[1 2 3]
[4 5 6]]
[['1' '2' '3']
['4' '5' '6']]
zeros 和 ones 函数可以创建指定长度或形状的全0或全1数组。
np.ones(6)
array([1., 1., 1., 1., 1., 1.])
创建初始值为0终值为1步长为0.1的等差数组
np.arange(0, 1, 0.1)
array([ 0. , 0.1 0.2 0.3, 0.4 0.5 0.6, 0.7, 0.8 0.9])
创建初始值为0终值为1元素个数为10的等差数组
np.linspace(0, 110) # 步长为 1/9lin是linear的缩写
arnay([ 0. , 0.11111111, 0.22222222, 0.33333333, 0.44444444,
0.55555556, 0.66666667, 0.77777778, 0.88888889, 1. ])
创建从10的0次方到10的平方共5个元素的等比数列
np.logspace(0, 2, 5)
array([ 1. , 3.16227766, 10. , 31.6227766 , 100. ])
numpy.random.rand(d0, d1, ..., dn):生成一个[0,1)之间的随机浮点数或N维浮点数组。
#生成2行3列的随机数数组值在[0,1)之间
numpy.random.rand(2, 3)
numpy.random.randn(d0, d1, ..., dn)生成一个浮点数或N维浮点数组取数范围正态分布的随机样本数。
生成2行3列的随机数数组值为正态分布的随机样本数
numpy.random.randn(2, 3)
生成包含10个元素的值在[0,100) 的数组
np.random.randint(0, 100, 10)
生成2*3维的值在[0,100) 的数组
np.random.randint(0, 100, (2,3))
迭代法计算斐波那契数列
n=()
a,b=0,1
for i in range(n):
a,b=b,a+b
print(b)