On Monday 04 July 2005 06:11 am, Brian van den Broek wrote: > As a self-directed learning exercise I've been working on a script to > convert numbers to arbitrary bases. It aims to take any of whole > numbers (python ints, longs, or Decimals), rational numbers (n / m n, > m whole) and floating points (the best I can do for reals), and > convert them to any base between 2 and 36, to desired precision.
Interesting, I'd like to see that. > I'm pretty close but I know I am not handling the precision quite > right. Nothing other than understanding hangs on it, but, that's > enough :-) Okay. You do understand that many numbers that can be exactly represented in one base cannot be in another? E.g. in base 3, one-third is 0.1, but in base 10, it's a repeating decimal: 0.3333333.... And of course, there are infinitely many other examples. So what you're really doing is trying to make sure that you don't *lose* precision in the conversion, *except* due to this point. I.e. you want to do the best you can do. I would say that if you have a number of places past the decimal point, that can be interpreted as the error of the representation: 1/3 ~= 0.33333 base10 +- 0.000005 Needless to say, the conventional floating point numbers in Python are actually stored as *binary*, which is why there is a "decimal" module (which is new). If you're going to be converting between bases anyway, it probably makes little difference whether you are using the decimal module or not, of course. You'll have the same problems the conventional float numbers do. Getting back to your precision problem: I bet if you simply evaluate the error term as I have above, and then convert *that* into your base of choice, you will be able to tell how many places are correct in the conversion. That is to, say, stop think about "number of places" and instead think about "representation error". That number is a real property of the data which can be represented in any base. Then you can convert it to number of places in the representation process. e.g. 0.000005 has 6 places behind the zero in decimal, how many does base3(0.000005)? --- that's the accuracy of the statement 0.33333 base10 ~= 0.1 base3 +- base3(0.000005 base10) Roughly, we know that 0.000005 = 10^-5 / 2. The same term in base 3 will be 3^-x/2 = 10^5/2 places, which can be solved using logarithms, but I'll "leave that as an excercise for the reader", because I'm too lazy to go look it up, and I've forgotten the details. ;-) I hope this is helpful, though, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com -- http://mail.python.org/mailman/listinfo/python-list