+ 2
Is there a way to properly represent repeating decimals in Python?
For instance, I want to get the input 0.(3), or .3 repeating, and then convert it to a fraction (and get 1/3). Right now it works if I just enter 1.3333333 as Python equates it to 1.3 repeating. Is there a better way to do it, though?
4 ответов
0
What s your goal? And what accuracy do you need?
There is always rounding issues when you use floats numbers.
A computer cannot hold infinite numbers of digits in its memory...
If precision is an issue, maybe you can try the fractions module to stor number as a fraction.
0
Loïc Mahé my goal is described in the question. Get the number as an input in the format of a decimal (e.g. 0.(3) that would stand for .3 repeating) and then convert it to the fraction 1/3. I know that a computer can't hold infinite numbers in its memory, but calculators have a way of knowing when a number is a repeating decimal. If you divide 1/3, it will show 0.333333... and treat that decimal as if it has an infinite number of 3's. If I later multiply this number by 6, it will show 2 rather than something like 1.998
0
If you have some code which already works please show us... Otherwise there is no easy way to handle this... The fractions module will probably allow you to keep the best accuracy.
0
Computers often works with float, which have a limited precision, and so cannot handle infinetly repeating numbers. Only the fractions module can keep the accuracy of such numbers. Look at Miika post, it is very good.