Re: [Sbcl-help] Odd Division By Zero Error From: Jeffrey Cunningham - 2012-07-09 00:01:27 Attachments: Message as HTML ```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. 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). Jeff Cunningham ```