If you just want arbitrary precision arithmetic, use the Fraction
class within the fractions
module, which is part of the standard library. When you're done with your calculations, you can convert it to a float (if you must). Unfortunately, the resultant float may not be arbitrary precision, but all the calculations up until the conversion to a float will be, and thus your float will likely be more accurate than if you were using floats the whole time.
Really, if you don't care about the visual, just keep the number a Fraction the whole time and your problem is solved. If you do care about seeing a decimal point, you'll need to realize that arbitrary precision in that case is going to be a rather involved process, because then you have to deal with repeating values (like a third is a bunch of threes forever, after 0.
). Nevertheless, there are people out there who try to solve the problem. Getting it accurate up to a certain decimal point should certainly be possible, but don't expect more than that if you're not using Fractions.
Fractions have numerators and denominators (which are stored as longs, I believe, and longs in Python are already arbitrary precision; so, you can have numbers as big as you like for both the numerator and the denominator). I wrote some code for converting fractions from 1234/12
style to 2 3/4
style. But, I don't want to give it a CC license by posting it here (I'd rather a real software license, such as MIT). So, you'll have to let me know if you're interested.
Here are examples of how to use fractions.Fraction
:
from fractions import Fraction
x=Fraction("2.234532456345265356356356354624356356235635634563563565635645") #You can add string numbers of any value.
y=Fraction(1, 3234524352345) #This is one 3234524352345th
x+=5 #adding five (The five doesn't have to be a Fraction object, but the result will be one.)
y=x/y #Dive x by y.
x=float(x) #Converting it into a float
Anyway, you can treat them just like any other kind of number. You can convert things to fractions the same as you would to integers (e.g. Fraction(4.2343)
will convert the float to a Fraction). You can round them, or whatever, too.
I find that Fraction class to be vastly under-represented. I use it a lot. It's awesome.