Revision: 20747
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at November 24, 2009 08:48 by Zufolek
Initial Code
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <assert.h> //define NDEBUG if you want to remove asserts //the following function //returns a random non-negative integer less than h //h must obviously be less than or equal to the highest number //possible from the random number generator int rnd(int h){ if(!h)return 0;//making sure we don't divide by zero! assert(h<=RAND_MAX); return rand()%h; } //rolls a virtual die //(die is the singular of dice) //returns a number 1-6 int rolldie(){ return rnd(6)+1; } //flips a virtual coin //returns 1 or 0 for heads or tails int flipcoin(){ return rand()&1; } //returns a floating point number in range 0 to 1 double frand(){ return rand()/((double)RAND_MAX+1); } //returns random floating point number in range 0 to f double frnd(float f){ return frand()*f; } //returns 1 (true) at probability p //example: //prob(0.7) will be true 70% of the time int prob(float p){ if(frand()<p)return 1; return 0; } //returns distance between two points in 2 dimensions double dist2d(float x1,float y1,float x2,float y2){ float dx=x1-x2; float dy=y1-y2; return sqrt(dx*dx+dy*dy); } //returns distance between two points in 3 dimensions double dist3d(float x1,float y1,float z1,float x2,float y2,float z2){ float dx=x1-x2; float dy=y1-y2; float dz=z1-z2; return sqrt(dx*dx+dy*dy+dz*dz); } //Like % (modulus) but works "correctly" for negative values signed int zmod(signed int a,unsigned int b){ signed int c=0; if(!b)return c;//making sure we don't divide by zero if(a<0)--a; c=a%b; return c; } //returns volume of sphere having radius r //the parentheses may help compiler optimize double spherevolume(float r){ return (M_PI*4/3)*(r*r*r); } //returns surface area of sphere having radius r double spheresurface(float r){ return (M_PI*4)*(r*r); }
Initial URL
Initial Description
Functions for generating random numbers, flipping coins, rolling dice, etc.
Initial Title
Some handy math functions
Initial Tags
Initial Language
C