[Tutor] cube root
Andre Engels
andreengels at gmail.com
Mon Jan 19 13:22:59 CET 2009
On Mon, Jan 19, 2009 at 1:13 PM, spir <denis.spir at free.fr> wrote:
> Do you know any common algorithm to convert decimal (in the sense of fractional) decimals (in the sense of base 10 numbers) into binaries?
>
> 123.456 --> 1111011.bbb...
> and/or
> 123456 * 10**(-3) --> bbb... * 2**(-bbb...)
>
> How do python/C achieve that?
There's probably more efficient methods, but a simple method to
convert a decimal fraction to a binary would be the following
(untested):
def tobinary(n,precision=12)
# n is a number between 0 and 1 that should be converted,
precision is the number of binary digits to use.
assert 0.0 <= n < 1.0
outcome = "0."
compare = 0.5
for i in xrange(precision):
if n > compare:
outcome += "1"
n -= compare
if n == 0.0: break
else:
outcome += "0"
compare /= 2
return outcome
--
André Engels, andreengels at gmail.com
More information about the Tutor
mailing list