Is 0.000001 as small a number as can be worked with?

Michael Julian Lew michaell at unimelb.edu.au
Thu Dec 5 05:17:34 EST 2013


Ages ago I wrote some functions to allow arithmetic with arbitrarily large numbers of decimal places. (I think I debugged them, but it was a while ago so you should check them carefully!)

function SciForm x
   --Returns the number in the form signed mantissa, comma, power of ten
   put empty into tsign
   if char 1 of x = "-" then 
      delete char 1 of x
      put "-" into tsign
   end if
   if char 1 of x = "+" then delete char 1 of x
   --leading zeros
   repeat
      if char 1 of x <> "0" then exit repeat
      delete char 1 of x
   end repeat
   if x is empty then
      --value was zero!
      return "0,0"
      exit SciForm
   end if
   if "." is not in x then 
      put (the number of chars in x) -1 into tpower
      put "." after char 1 of x
      put x into tmant
   else --contains .
      if char 1 of x = "." then --decimal leading
         replace "." with empty in x
         put x into x2
         put x into tmant
         put "." after char 1 of tmant
         put 0 into leadZeros
         repeat
            if char 1 of x2 <> "0" then exit repeat
            delete char 1 of x2
            add 1 to leadZeros
         end repeat
         if x2 is empty then
            --value was zero!
            return "0,0"
            exit SciForm
         end if
         put the number of chars in x2- the number of chars in x -1 into tpower
         if leadZeros > 0 then delete char 1 to leadZeros of x
         put "." after char 1 of x
         put x into tmant
      else --decimal within
         put offset(".",x)-2 into tpower
         replace "." with empty in x
         put "." after char 1 of x
         put x into tmant
      end if
   end if
   return tsign & tmant &"," & tpower
end SciForm

function SciFormMult x,y --returns x*y
   put item 2 of x + item 2 of y into tpower
   put item 1 of x*item 1 of y into tMantProd
   put SciForm(tMantProd) into tProd
   add tPower to item 2 of tProd
   return tProd
end SciFormMult

function SciFormDivide x,y --returns x/y
   put item 2 of x - item 2 of y into tpower
   put item 1 of x/item 1 of y into tMantDiv
   put SciForm(tMantDiv) into tDiv
   add tPower to item 2 of tDiv
   return tDiv
end SciFormDivide

function SciFormAdd x,y
   put item 2 of x into xp
   put item 2 of y into yp
   put xp-yp into pdiff
   put item 1 of x into xmant
   put item 1 of y into ymant
   multiply ymant by 10^-pdiff
   put ymant + xmant into mantSum
   put sciForm(mantSum) into tsum
   add xp to item 2 of tsum
   return tsum
end SciFormAdd

function sciFormSubtract x,y
   multiply item 1 of y by -1
   return SciFormAdd(x,y)
end sciFormSubtract




More information about the Use-livecode mailing list