Re: power overflow
- Posted by jluethje at gmx.de Jun 03, 2002
- 425 views
Hi tone, nice idea to write this function. With two changes, it really will be safe, I think. > Thanks, here is general function I wrote safe_power(): > global constant LOWEST_ATOM = -1e300 > global constant HIGHEST_ATOM = +1e300 > global function log_general (atom b, object x) > -- general log() function > -- logarithm for base b and number (or sequence) x > -- in : b: positive real number, != 1 > -- x: positive real number (or sequence of those numbers) > -- out: real number -- (x = 1 -->> function returns 0 for any base b) > return log (x) / log (b) > end function > --/* > -- safe_power [Created on 3. June 2002, 17:59] > -- The 'safe_power' function does same thing as Euphoria builtin 'power()' > -- with this difference: if return value of 'power()' is too big > -- interpreter crashes with error mesage math overflow. > -- If in this function returned value would be too big > -- then error 'HIGHEST_ATOM' is returned. > -- > -- PARAMETERS > -- 'a' > -- Same as in built in 'power()'. > -- 'b' > -- Same as in built in 'power()'. > -- > -- RETURN VALUES > -- The value of power(), or error value 'HIGHEST_ATOM' > --*/ > global function safe_power (atom a, atom b) > atom b_max --// if 'b' is bigger or equal than this then overflow > atom a_max --// if 'a' is bigger or equal than this then overflow -- Additionally: if a = 0 and b = 0 then return "power(0,0) is not defined" end if > if a = 0 or b = 0 then --// log (0) crashes -- Change previous line -- (see my comments in global function log_general() above): if a <= 0 or b <= 0 or a = 1 then > return power (a ,b) > end if > b_max = log_general (a, HIGHEST_ATOM) > if b >= b_max then > return HIGHEST_ATOM > end if > a_max = power (HIGHEST_ATOM, 1 / b) > if a >= a_max then > return HIGHEST_ATOM > end if > return power (a, b) > end function For more information about logarithms, see http://mathworld.wolfram.com/Logarithm.html Best regards, Juergen