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

hongy...@gmail.com hongyi.zhao at gmail.com
Mon May 16 19:31:07 EDT 2022


On Tuesday, May 17, 2022 at 7:11:24 AM UTC+8, hongy... at gmail.com wrote:
> On Monday, May 16, 2022 at 11:27:58 PM UTC+8, Dennis Lee Bieber wrote: 
> > On Mon, 16 May 2022 02:03:26 -0700 (PDT), "hongy... at gmail.com" 
> > <hongy... at gmail.com> declaimed the following: 
> > 
> > 
> > >print(lst) 
> > 
> > Printing higher level structures uses the repr() of the structure and 
> > its contents -- theoretically a form that could be used within code as a 
> > literal. If you want human-readable str() you will need to write your own 
> > output loop to do the formatting of the structure, and explicitly print 
> > each item of the structure.
> Thank you for your explanation. I have come up with the following methods: 
> ``` 
> 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]] 
> import numpy as np 
> from fractions import Fraction 
> import re 
> 
> def strmat(m): 
> if(np.array([m]).ndim==1): 
> return str(Fraction(m)) 
> else: return list(map(lambda L:strmat(L), np.array(m))) 
> 
> a=str(strmat(b)) 
> a=re.sub(r"'","",a) 
> repr(a) 
> print(repr(a)) 
> '[[0, -1, 0, 1/4], [1, 0, 0, 1/4], [0, 0, 1, 1/4], [0, 0, 0, 1]]' 
> ``` 
> Best, 
> HZ

See here [1] for the related discussion.

[1] https://discuss.python.org/t/convert-the-decimal-numbers-expressed-in-a-numpy-ndarray-into-a-matrix-representing-elements-in-fractional-form/15780


More information about the Python-list mailing list