Integer division

Doug Gwyn gwyn at brl-smoke.ARPA
Fri Feb 14 18:54:44 AEST 1986


>... Since
>the work involved was massive, I saved the operands, the quotient,
>and the remainder.  If subsequent calls had the same operands, I
>just returned the already-computed values!

This is a nice example of a "good idea".  It paid off because long
division was frequently accompanied by long remainder with the same
operands, and the extra bookkeeping overhead per call was more than
compensated by the average computational savings.  Thanks, Joe.
The obvious generalization can be applied in a variety of codes.
A conceptually related example is:

/*
	RnNorm -- random normal deviate with specified mean & std. dev.

	last edit:	86/01/04	D A Gwyn

	SCCS ID:	@(#)rnnorm.c	1.1

Method:
	Polar method; see Knuth 3.4.1C(1)
*/

#include	<math.h>

#include	<random.h>		/* defines RnFlt() (uniform range) */
#include	<std.h>			/* defines "bool", "true", "false" */

double
RnNorm( mu, sigma )			/* return range (-inf,inf) */
	double		mu;		/* desired mean */
	double		sigma;		/* desired std. deviation */
	{
	static bool	saved = false;	/* "have saved value" flag */
	static double	rndsave = 0.0;	/* saved value iff `saved' */
	double		s, x, y;

	if ( saved )
		{
		x = rndsave;	 	/* already on hand */
		saved = false;		/* now used up */
		}
	else	{
		/* generate a pair of numbers */

		do	{
			x = RnFlt( -1.0, 1.0 );
			y = RnFlt( -1.0, 1.0 );
			s = x * x + y * y;
			}
		while ( s >= 1.0	/* 0.25 probability */
		     || s == 0.0	/* practically never */
		      );

		rndsave = sqrt( -2.0 * log( s ) / s );
		x *= rndsave;
		rndsave *= y;			/* save for next call */
		saved = true;
		}

	return mu + sigma * x;
	}



More information about the Comp.lang.c mailing list