Complex Numbers & binary fractions

Cubist at aol.com Cubist at aol.com
Mon Sep 12 15:23:08 EDT 2005


sez beat.c at hetnet.nl:
>has anyone made a library for working with complex numbers? And is 
>willing to share this with me? I'm also looking for some code to 
>convert decimal fractions (i.e. 0.56384) to binary  fractions.
   Haven't played with complex numbers, sorry. For converting decimal 
fractions to binary, however, something like this might work:

function DecFrac2BinFrac TheFrac, ThePrecision
  # TheFrac is *assumed* to have nothing to the *left* of the decimal point
  # ThePrecision is *assumed* to be a positive integer
  # you can write the code to handle those cases yourself, if need be, right?

  if ThePrecision = "" or ThePrecision < 1 then put 10 into ThePrecision
  # so the user can just supply a fraction and not care

  set the numberFormat to "0.#####"
  #you want to make sure there's a leading 0 before the decimal
  put "." into Rezult
  repeat # yes, it's an infinite loop. the escape test will be inside it
    multiply TheFrac by 2
    put char 1 of TheFrac after Rezult
    # because of numberFormat, char 1 here should be either 0 or 1
    if the length of TheFrac > ThePrecision  or TheFrac = 0 then exit repeat
    delete char 1 of TheFrac
  end repeat
  return Rezult
end DecFrac2BinFrac

   You really do have to worry about the precision of the result. Most 
decimal fractions simply don't *have* exact representations in binary; unless you 
explicitly define the precision, thus telling the code when to bail out, any 
non-binary-exact decimal fractions will cause the code to grind along forever, or 
until the growing length of the binary representation overfills all available 
RAM. Not good.

   Hope this helps...



More information about the use-livecode mailing list