如何使用 NumPy 禁止对小数使用科学记数法?
有时,我们有采用科学记数法的元素,为了简单起见,我们不得不隐藏科学记数法。为此,我们调用了一个名为numpy.set_printoptions()的函数。此函数将有助于抑制科学记数法和显示数字到一定的精度。
Syntax: numpy.set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None, formatter=None, sign=None, floatmode=None, *, legacy=None)
Parameters:
- precision: Number of digits of precision for floating point output (default 8)
- suppress: If True, always print floating point numbers using fixed point notation, if False, then scientific notation is used when absolute value of the smallest number is < 1e-4
Rest of the parameters are optional.
示例 1:
Python3
# Importing Numpy library
import numpy as np
# Creating a 1-D Numpy array
num = np.array([1.8e-10, 1.586, 150.45, 0.2855])
# Suppressing 1-D numpy array with precision 2
# using numpy.set_printoptions()
print("Numpy array values with precision 2:\n")
np.set_printoptions(precision = 2, suppress = True)
print(num)
Python3
# Importing Numpy library
import numpy as np
# Creating a 2-D Numpy array
num = np.array([[3.1415, 2.7182],
[6.6260e-34, 6.6743e-11]])
# Suppressing 2-D numpy array with precision 3
# using numpy.set_printoptions()
print("Numpy array values with precision 3:\n")
np.set_printoptions(precision = 3, suppress = True)
print(num)
Python3
# Importing Numpy library
import numpy as np
# Creating a 3-D Numpy array
num = np.array([[[3.141527, 2.718283],
[6.6268574, 6.6743e-11]],
[[34.8454, 8.6260e-34],
[7, 8]]])
# Suppressing 3-D numpy array with precision 4
# using numpy.set_printoptions()
print("Numpy array values with precision 4:\n")
np.set_printoptions(precision = 4, suppress = True)
print(num)
输出:
在上面的示例中,我们以精度 2抑制了1-D NumPy 数组元素的科学记数法。
示例 2:
蟒蛇3
# Importing Numpy library
import numpy as np
# Creating a 2-D Numpy array
num = np.array([[3.1415, 2.7182],
[6.6260e-34, 6.6743e-11]])
# Suppressing 2-D numpy array with precision 3
# using numpy.set_printoptions()
print("Numpy array values with precision 3:\n")
np.set_printoptions(precision = 3, suppress = True)
print(num)
输出:
在上面的示例中,我们以精度 3抑制了2-D NumPy 数组元素的科学记数法。
示例 3:
蟒蛇3
# Importing Numpy library
import numpy as np
# Creating a 3-D Numpy array
num = np.array([[[3.141527, 2.718283],
[6.6268574, 6.6743e-11]],
[[34.8454, 8.6260e-34],
[7, 8]]])
# Suppressing 3-D numpy array with precision 4
# using numpy.set_printoptions()
print("Numpy array values with precision 4:\n")
np.set_printoptions(precision = 4, suppress = True)
print(num)
输出:
在上面的示例中,我们以精度 4抑制了3-D NumPy 数组元素的科学记数法。