python - How to convert a decimal number into fraction? -
I was wondering how to convert a decimal to its lowest form in Python in its lowest form.
Example:
0.25 - & gt; 1/4 0.5 - & gt; 1/2 1.25 - & gt; 5/4 3 - & gt; 3/1
You have two options:
- < Li>
- P> Use it:
& gt; & Gt; & Gt; Fractions from Fractions & gt; & Gt; & Gt; Fraction (0.25) fraction (1, 4)
Use:
& gt; & Gt; & Gt;
is very helpful in the latter str ()
conversion:
& gt; & Gt; & Gt; Str (fraction (0.25)) '1/4'> gt; & Gt; & Gt; Print fractions (0.25) 1/4
Because floating point variants may be incomplete, you can eliminate 'weird' fractions; Limit everything to 'smooth' part to a certain extent:
& gt; & Gt; & Gt; Fraction (0.185) degree (3332663724254167, 1801439850 9 481984)> gt; & Gt; & Gt; Fraction (0.185) .limit_denominator () fraction (37, 200)
If you are using Python 2.6, then fraction ()
to pass so far Does not support directly in a float
, but you can combine two technologies in the top:
fraction (* 0.25.as_integer_ratio ())
or you can use it only:
Fraction.from_float (0.25)
Which essentially does the same thing, like take the integer ratio tube And pass it as two different arguments.
And a small demo with your sample values:
gt; & Gt; In F (0.25, 0.5, 1.25, 3.0): ... print f.as_integer_ratio () ... print repr (calibration (f)), fraction (f) ... (1, 4) fraction (1, 4) ) 1/4 (1, 2) fraction (1, 2) 1/2 (5, 4) fraction (5, 4) 5/4 (3, 1) fraction (3, 1) 3
<< / P>
Comments
Post a Comment