【Python】numpy和math库中的函数

1. math.fabs(x): 返回x的绝对值。同numpy。

>>> import numpy
>>> import math
>>> numpy.fabs(-5)
5.0
>>> math.fabs(-5)
5.0

2.x.astype(type): 返回type类型的x, type 一般可以为numpy.int,
numpy.float等,没有math.int等

>>> import numpy as np
>>> d = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], dtype=np.float)
>>> f=d.astype(np.int)
>>> print f
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
>>> d
array([[  1.,   2.,   3.,   4.],
       [  5.,   6.,   7.,   8.],
       [  9.,  10.,  11.,  12.]])

3. numpy.frompyfunc(func, para_size, valu_size): 将一个计算单个元素的函数func 转换成计算能计算多个元素的函数,返回类型为object。

>>> f=np.frompyfunc(np.fabs, 1,1)
>>> f([-1,-2,-3,-4])
array([1.0, 2.0, 3.0, 4.0], dtype=object)

4. numpy.zeros_like(x): 返回一个用0填充的跟输入数组形 x 状和类型一样的数组。类似的还有 np.ones_like(), np.empty_like(), math包没有该函数。

>>> d
array([[  1.,   2.,   3.,   4.],
       [  5.,   6.,   7.,   8.],
       [  9.,  10.,  11.,  12.]])
>>> np.zeros_like(d)
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])
>>> np.empty_like(d)
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])
>>> np.ones_like(d)
array([[ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.]])

5. numpy.exp(x): 返回e的x次方, math函数同此。

>>> np.exp(2)
7.3890560989306504
>>> math.exp(2)
7.38905609893065

6. numpy.sqrt(x): 返回x的平方根, math函数同此。


>>> math.sqrt(2)
1.4142135623730951
>>> numpy.sqrt(2)
1.4142135623730951
>>> numpy.sqrt(4)
2.0

7. numpy.e, numpy.pi: 引用e, pi, math函数同此。

>>> np.e
2.718281828459045
>>> np.pi
3.141592653589793
>>> math.e
2.718281828459045
>>> math.pi
3.141592653589793

转载自:https://www.cnblogs.com/no-tears-girl/p/6962832.html

发布了33 篇原创文章 · 获赞 7 · 访问量 4547

猜你喜欢

转载自blog.csdn.net/qq_45239614/article/details/103110659