![]() ![]() I found a much simpler way to resolve the accuracy issue. The mathematical result desired was 8857097/10000000 which can be achieved by casting to a string and then manipulating it. To expand upon Martijn Pieters excellent answer with an additional option due to the imprecision inherent with more complex floats. take the integer ratio tuple and pass that in as two separate arguments.Īnd a small demo with your sample values: > for f in (0.25, 0.5, 1.25, 3.0):īoth the fractions module and the float.as_integer_ratio() method are new in Python 2.6. Which essentially does the same thing, e.g. Or you can just use the om_float() class method: om_float(0.25) If you are using Python 2.6 still, then Fraction() doesn't yet support passing in a float directly, but you can combine the two techniques above into: Fraction(*0.25.as_integer_ratio()) The latter has a very helpful str() conversion: > str(Fraction(0.25))īecause floating point values can be imprecise, you can end up with 'weird' fractions limit the denominator to 'simplify' the fraction somewhat, with Fraction.limit_denominator(): > Fraction(0.185)įraction(3332663724254167, 18014398509481984) ![]() ![]() Use the fractions.Fraction() type: > from fractions import Fraction (as of Python 3.6, you can do the same with a decimal.Decimal() object.) Use float.as_integer_ratio(): > (0.25).as_integer_ratio() ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |