[Tutor] cube root

Ken Oliver ksterling at mindspring.com
Mon Jan 19 14:46:21 CET 2009



-----Original Message-----
>From: Andre Engels <andreengels at gmail.com>
>Sent: Jan 19, 2009 7:22 AM
>To: spir <denis.spir at free.fr>
>Cc: tutor at python.org
>Subject: Re: [Tutor] cube root
>
>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

I hope my memory serves.  To convert decimal fraction into binary fraction, do the following repeatedly to the decimal until desired accuracy is achieved.

Multiply by 2, if result is less than 1, next digit is 0 else next digit is 1 and you drop the whole number part of the result. Continue...

.456 * 2 = .912    (first digit is 0)
.912 * 2 = 1.824   (next digit is 1)
.824 * 2 = 1.648   (next digit is 1)
.648 * 2 = 1.296   (next digit is 1)
.296 * 2 = .592    (next digit is 0)

0.456 ~ 0.01110


More information about the Tutor mailing list