pythonsympy

sympy matrix scientific notation


I'm trying to display a sympy matrix in scientific notation, and it is only working for values less than 1. I can't understand why applyfunc is behaving differently. Is there a better way to do this?

import numpy as np
from sympy import Matrix
from sympy.printing import latex
from IPython.display import display

C = np.array([
    [390, 145, ],
    [145, 0, ],
    ])*1e9

S_ij = np.linalg.inv(C)
S_scientific = Matrix(S_ij).applyfunc(lambda x: '{:.2e}'.format(float(x)))
print('this prints as desired:')
display(S_scientific) #m^2 / N 

def g(x):
    #shouldn't be necessary since 0 handles fine above
    if abs(float(x.evalf())) < 1e-10:
        return '0'
    else:
        return f'{float(x.evalf(8)):.2e}'
C_scientific = Matrix(C).applyfunc(g)
print()
print('this is not print in scientific notation:')
display(C_scientific) 
print(C_scientific)

And the output is, with a check on the function g: console output


Solution

  • I don't use SimPy but it seems this might be a workaround for you.

    Here for every matrix entry you force a desired precision with Float(number, precision). I guess if you don't make it by hand, SimPy falls back to its standard precision which results in large numbers.

    import numpy as np
    from sympy import Matrix, Float
    
    def formatter(x):
        return Float(x, 3)
    
    m = np.array([152000.0])
    m = Matrix(m).applyfunc(formatter)