## Re: [Sbcl-help] Odd Division By Zero Error

 Re: [Sbcl-help] Odd Division By Zero Error From: Burton Samograd - 2012-07-09 03:39:34 ```On 12-07-08 06:01 PM, Jeffrey Cunningham wrote: > > On 07/07/2012 08:02 PM, Jeffrey Cunningham wrote: >> >> On 07/07/2012 07:23 PM, Burton Samograd wrote: >>> On 12-07-07 07:03 PM, Kevin Reid wrote: >>>> On Jul 7, 2012, at 17:44, Burton Samograd wrote: >>>> >>>>> Here is the definition of normal, which has no divisions: >>>>> >>>>> (defun normal (&optional (a 1.0) (s 0.5)) >>>>> (+ a (* (sqrt (* -2 (log (random 1.0)))) (cos (* 2 pi (random 1.0))) s))) >>>>> >>>>> Any idea where this division by zero error might be coming from? >>>> RANDOM may return 0.0 in which case LOG will (on SBCL) signal DIVISION-BY-ZERO. >>>> >>> Ah, I had a feeling it was something like that but the division by zero >>> was throwing me off. >>> >>> Thanks. I got that line from Rosetta Code; maybe it should be fixed. >>> What is a good fix for this? I'm thinking that adding a very small value >>> to the result of random might suffice but I don't like it. >>> >>> -- >>> Burton Samograd >> >> Adding a small amount would warp the distribution (a tiny amount). >> But this will work and won't: >> >> (defun normal (&optional (a 1.0) (s 0.5)) >> (+ a (* (sqrt (* -2 (log (- 1.0 (random 1.0))))) (cos (* 2 pi >> (random 1.0))) >> s))) >> >> According to the spec, random produces numbers always less than the >> limit so it will never hit zero. And its a uniform distribution so >> you haven't changed its statistical properties. >> >> Jeff Cunningham >> > Have you looked at a distribution of the outputs? I'm wondering if > there's something else wrong. You really shouldn't see zero show up as > an argument to log except once in a blue moon. That was the problem. I'm running a simulation with hundreds of thousands of agents and that blue moon shows up pretty frequently. I tried your idea of subtracting from 1 on CCL (SBCL is being too finicky right now) and it doesn't seem to follow the standard of [0.0...1.0). I ended up just adding 1E-32 to (random 1.0); I really don't think it will make a difference (famous last words). > It might be very small numbers will kill log also. If that's the case, > then you could figure out the threshold for smallest argument to log, > and put some logic in there to exclude those cases (regen another > uniform variate). Maybe but since my tiny addition I haven't had the problem so I'm satisfied with it as a solution for now. > > Jeff Cunningham > -- Burton Samograd ```