numpy 如何强制python float不使用指数

tsm1rwdh  于 12个月前  发布在  Python
关注(0)|答案(1)|浏览(88)

我有一些问题,但这似乎是要点。
我有一些文本数字,用Python读入,乘以1000.0,然后使用,最后打印出来。
数据.Kin.X.L.值= -.800E-01-.750E-01 -.700E-01-.650E-01 -.600E-01-.550E-01 -.500E-01
所以,在multiply(1000.0)之后,值应该是(如果有就好了...):
New.vals =-80。-75-70-65-60-55-50
有时候,他们是(很少)。但它们通常保持指数形式:
典型值= -8.00E+01 -7.50E+01 -7.00E +01-6.50E +01-6.00E +01-5.50E +01-5.00E+01
我试过循环(x,n),但似乎不起作用。此外,这些是numpy数组中的值,如果这有任何区别的话。
这是用于创建打印输出的字符串的代码:

out = f'{k.strip()} = ' \
+ np.array2string(v,
                                        prefix=f'{k} = ',
                                        precision=5,
                                        max_line_width=200,
                                        floatmode='maxprec') + '\n'

更新:
我很快就会结束这一切。总体最佳工作答案是用途:
np.set_printoptions(suppress=True)
如果需要,您可以扩展精度,以便覆盖不会“旅行”,并将它们保留在科学计数法中。大于8的:
np.set_printoptions(precision=10)
它与numpy如何打印出数据无关,尽管它确实与numpy有关。

2q5ifsrm

2q5ifsrm1#

据我所知,没有任何选项可用于设置一个值,当超过该值时会触发科学计数法。但是,您可以定义自己的字符串生成函数:

import numpy as np

def arr2str(arr, big=1e3, small_precision=0, big_precision=2):
    """Convert 1D array with floats to string.
    
    Parameters
    ----------
    arr : np.ndarray[float]
        To-be-converted array.
    big : float, optional
        Numbers for which the absolute value is >= `big` are considered big and
        will be printed in scientific notation. Otherwise the number is
        considered small and will not be printed in scientific notation.
    small_precision : float, optional
        Precision for small numbers.
    big_precision : float, optional
        Precision for big numbers.
    
    Returns
    -------
    str
    
    """
    # Check input validity
    if not arr.ndim == 1:
        raise ValueError("Array does not have a dimension of one")
    if not isinstance(arr[0], np.floating):
        raise ValueError("Array does not contain floats")
        
    str_list = []
    for ele in arr:
        if abs(ele) >= big:
            str_list.append(f'{ele:.{big_precision}e}')
        else:
            str_list.append(f'{ele:.{small_precision}f}')
    string = ' '.join(str_list)
    string = '[' + string + ']'
    return string

# Usage example
example_arr = np.array([-80., -75., -70., -65., 55., -50., 4294, -64921])
print(arr2str(example_arr))

打印:

[-80 -75 -70 -65 55 -50 4.29e+03 -6.49e+04]

相关问题