On Thu, Oct 08, 2020 at 11:58:04AM -0400, Random832 wrote:
I was making a "convert Fraction to Decimal, exactly if possible" function and ran into a wall: it's not possible to do some of the necessary operations with exact precision in decimal:
Of course you can't do them with *exact* precision in Decimal, because that only has a fixed precision. (User-configurable, but fixed.) py> from decimal import Decimal py> from fractions import Fraction py> x = Fraction(1, 3) py> Decimal(x.numerator)/x.denominator Decimal('0.3333333333333333333333333333') Is that not sufficient? That is as close to exact as possible with the default Decimal context. If you want more precision, you can adjust the context. py> from decimal import localcontext py> with localcontext() as ctx: ... ctx.prec = 50 ... Decimal(1)/3 ... Decimal('0.33333333333333333333333333333333333333333333333333') I presume you understand that most fractions can not be represented as *exact* Decimals, no matter how many digits of precision you set. So I don't quite understand what you are trying to do, or why Decimal doesn't already do what you are trying to do. It might help if you can show an example of what you would like to do, but currently can't. Related: why doesn't Decimal support direct conversion from Fraction? -- Steve