Convert the decimal numbers expressed in a `numpy.ndarray` into a matrix representing elements in fractional form

Cousin Stanley cousinstanley at gmail.com
Wed May 18 17:26:02 EDT 2022


#!/usr/bin/env python3

'''
     NewsGroup .... comp.lang.python

     Subject ...... Convert the decimal numbers
                    expressed in a numpy.ndarray
                    into a matrix representing elements
                    in fractiona

     Date ......... 2022-05-16

     Post_By ...... hongy...

     Edit_By ...... Stanley C. Kitching
'''

import numpy as np

from fractions import Fraction

b = [
   [ 0.0 , -1.0 , 0.0 , 0.25 ] ,
   [ 1.0 ,  0.0 , 0.0 , 0.25 ] ,
   [ 0.0 ,  0.0 , 1.0 , 0.25 ] ,
   [ 0.0 ,  0.0 , 0.0 , 1.0  ] ]

a = [ ]

print( '\n  b .... \n' )

for row in b :
     arow = []
     print( '    ' , row )

     for dec_x in row :
         frac_x = Fraction( dec_x )
         arow.append( frac_x )

     a.append( arow )


# using f-string format

print( '\n  a .... \n' )

for row in a :

     for item in row :

         print( f'    {item} ' , end = '' )

     print()

# ------------------------------------------

-- 
Stanley C. Kitching
Human Being
Phoenix, Arizona


More information about the Python-list mailing list