How to force a python float to not use exponents

87 Views Asked by At

I have some code that reads numbers into a floating-point Numpy array (from a text format), multiplies the values by 1000.0, and later prints the array.

I format the array for printing like so, where k is a string identifying the array and v is the array itself:

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

I would like to see results that look like:

New.vals =         -80. -75. -70. -65. -60. -55. -50.

But usually I get a result using scientific notation:

Typical.vals =         -8.00E+01 -7.50E+01 -7.00E+01 -6.50E+01 -6.00E+01 -5.50E+01 -5.00E+01

How can I enforce formatting without scientific notation?

1

There are 1 best solutions below

0
Xukrao On

To the best of my knowledge there is no option available for setting a value that when exceeded triggers scientific notation. However you can define your own string-generating function:

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))

prints:

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