Board logo

标题: Numpy(科学计算包)- 【算术函数】 [打印本页]

作者: 龙听    时间: 2024-3-13 10:55     标题: Numpy(科学计算包)- 【算术函数】

NumPy 算术函数包含简单的加减乘除: add(),subtract(),multiply() 和 divide()。

需要注意的是数组必须具有相同的形状或符合数组广播规则。

实例
  1. import numpy as np

  2. a = np.arange(9, dtype = np.float_).reshape(3,3)  
  3. print ('第一个数组:')
  4. print (a)
  5. print ('\n')
  6. print ('第二个数组:')
  7. b = np.array([10,10,10])  
  8. print (b)
  9. print ('\n')
  10. print ('两个数组相加:')
  11. print (np.add(a,b))
  12. print ('\n')
  13. print ('两个数组相减:')
  14. print (np.subtract(a,b))
  15. print ('\n')
  16. print ('两个数组相乘:')
  17. print (np.multiply(a,b))
  18. print ('\n')
  19. print ('两个数组相除:')
  20. print (np.divide(a,b))
复制代码
输出结果为:
  1. 第一个数组:
  2. [[0. 1. 2.]
  3. [3. 4. 5.]
  4. [6. 7. 8.]]


  5. 第二个数组:
  6. [10 10 10]


  7. 两个数组相加:
  8. [[10. 11. 12.]
  9. [13. 14. 15.]
  10. [16. 17. 18.]]


  11. 两个数组相减:
  12. [[-10.  -9.  -8.]
  13. [ -7.  -6.  -5.]
  14. [ -4.  -3.  -2.]]


  15. 两个数组相乘:
  16. [[ 0. 10. 20.]
  17. [30. 40. 50.]
  18. [60. 70. 80.]]


  19. 两个数组相除:
  20. [[0.  0.1 0.2]
  21. [0.3 0.4 0.5]
  22. [0.6 0.7 0.8]]
复制代码
此外 Numpy 也包含了其他重要的算术函数。

numpy.reciprocal()

numpy.reciprocal() 函数返回参数逐元素的倒数。如 1/4 倒数为 4/1。

实例
  1. import numpy as np

  2. a = np.array([0.25,  1.33,  1,  100])  
  3. print ('我们的数组是:')
  4. print (a)
  5. print ('\n')
  6. print ('调用 reciprocal 函数:')
  7. print (np.reciprocal(a))
复制代码
输出结果为:
  1. 我们的数组是:
  2. [  0.25   1.33   1.   100.  ]


  3. 调用 reciprocal 函数:
  4. [4.        0.7518797 1.        0.01     ]
复制代码
numpy.power()

numpy.power() 函数将第一个输入数组中的元素作为底数,计算它与第二个输入数组中相应元素的幂。

实例
  1. import numpy as np

  2. a = np.array([10,100,1000])  
  3. print ('我们的数组是;')
  4. print (a)
  5. print ('\n')
  6. print ('调用 power 函数:')
  7. print (np.power(a,2))
  8. print ('\n')
  9. print ('第二个数组:')
  10. b = np.array([1,2,3])  
  11. print (b)
  12. print ('\n')
  13. print ('再次调用 power 函数:')
  14. print (np.power(a,b))
复制代码
输出结果为:
  1. 我们的数组是;
  2. [  10  100 1000]


  3. 调用 power 函数:
  4. [    100   10000 1000000]


  5. 第二个数组:
  6. [1 2 3]


  7. 再次调用 power 函数:
  8. [        10      10000 1000000000]
复制代码
numpy.mod()

numpy.mod() 计算输入数组中相应元素的相除后的余数。 函数 numpy.remainder() 也产生相同的结果。

实例
  1. import numpy as np

  2. a = np.array([10,20,30])
  3. b = np.array([3,5,7])  
  4. print ('第一个数组:')
  5. print (a)
  6. print ('\n')
  7. print ('第二个数组:')
  8. print (b)
  9. print ('\n')
  10. print ('调用 mod() 函数:')
  11. print (np.mod(a,b))
  12. print ('\n')
  13. print ('调用 remainder() 函数:')
  14. print (np.remainder(a,b))
复制代码
输出结果为:
  1. 第一个数组:
  2. [10 20 30]


  3. 第二个数组:
  4. [3 5 7]


  5. 调用 mod() 函数:
  6. [1 0 2]


  7. 调用 remainder() 函数:
  8. [1 0 2]
复制代码





欢迎光临 龙听期货论坛 (http://www.qhlt.cn/) Powered by Discuz! 7.2