Re: New proposal for math.e
- Posted by Juergen Luethje <j.lue at gmx??e> Aug 02, 2007
- 529 views
Matt Lewis wrote: > Juergen Luethje wrote: > > > > This is my new proposal for a "math.e" standard include file, > > according to the recent discussion on this forum. > > <snip> > > }}} <eucode> > global function log2 (object x) > -- logarithm base 2 > -- in : (sequence of) real number(s) > 0 > -- out: (sequence of) real number(s) > -- Note: This function returns _exact_ results for all integral > -- powers of 2 in the half-closed interval ]0,#FFFFFFFF] > > if atom(x) then > if x = #20000000 then > return 29 > elsif x = #80000000 then > return 31 > else > return log(x)/LN2 > end if > end if > > for i = 1 to length(x) do > x[i] = log2(x[i]) > end for > return x > end function > </eucode> {{{ > > I'm curious about the special treatment of #20000000 and #80000000 in log2. > I assume that rounding errors give you imprecise answers? Yes. When I wrote the function some time ago, only these two x values gave me imprecise answers, so I was happy that there were not so many special cases. > However, I > get the following imprecise results when taking out the special cases: > }}} <eucode> > for i = 0 to 32 do > printf(1, "%d: %0.16g\n", i & log2( power( 2, i ) )) > end for > </eucode> {{{ [snipped list of values that contains 11 imprecise results] I think I've found the answer. I have this function since a rather long time in my private math library, and I copied it into the code proposed for the Euphoria "math.e" file. In my original code which I had used for testing, it read return log(x)/log(2) Now, since we had constant LN2 = 0.6931471805599453 in "math.e" anyway, I thought it was a good idea to write return log(x)/LN2 instead. And as you showed here, that doesn't work as expected. When I again use return log(x)/log(2) in function log2(), then
for i = 0 to 32 do printf(1, "%d: %0.16g\n", i & log2( power( 2, i ) )) end for
prints 0: 0 1: 1 2: 2 3: 3 4: 4 5: 5 6: 6 7: 7 8: 8 9: 9 10: 10 11: 11 12: 12 13: 13 14: 14 15: 15 16: 16 17: 17 18: 18 19: 19 20: 20 21: 21 22: 22 23: 23 24: 24 25: 25 26: 26 27: 27 28: 28 29: 29 30: 30 31: 31 32: 32 even when I take out the special cases!! I can't exactly remember anymore, but probably I wrote and tested the function log2() on my old PC (Windows 98, Pentium II processor). Now I have Windows XP and a Centrino Duo Processor. Is it possible that the new system makes disappear the imprecise results? At least I currently have no other idea. And since in this case it's much better to use log(2) rather than LN2, maybe that means that it would be better not to provide such constants in "math.e"? I'm sorry. I have more questions than answers. Thanks for finding this. Regards, Juergen