I would like to print numeric values with decimals in their fraction form:
0.5 to 1/2 0.75 to 3/4 4.5 to 9/2
Is there a native library to perform the conversion? How is this conversion done?
I would like to print numeric values with decimals in their fraction form:
0.5 to 1/2 0.75 to 3/4 4.5 to 9/2
Is there a native library to perform the conversion? How is this conversion done?
You can use the
Fraction
module classfractions
:If you have the numbers saved as reals, then you can make the conversion explicit using
str
, and then pass that to theFraction
.You can make a recursive function that returns values for the numerator and denominator of the fraction, regardless of whether it is simplified or not. Then you simplify or factor using Euclid's algorithm.
Here is the code for the algorithm.
Then you do something like
numerador=numerador/mcd(numerador,denominador)
anddenominador=denominador/mcd(numerador,denominador)
and print it as a string:Using the
Fraction
module classfractions
, the value of the fraction is not returned when it has infinite decimal numbers, therefore it is necessary to add.limit_denominator()
after using the class.And as a result: