Some handy math functions


/ Published in: C
Save to your folder(s)

Functions for generating random numbers, flipping coins, rolling dice, etc.


Copy this code and paste it in your HTML
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. #include <assert.h>
  5.  
  6.  
  7. //define NDEBUG if you want to remove asserts
  8.  
  9.  
  10. //the following function
  11. //returns a random non-negative integer less than h
  12. //h must obviously be less than or equal to the highest number
  13. //possible from the random number generator
  14.  
  15. int rnd(int h){
  16. if(!h)return 0;//making sure we don't divide by zero!
  17. assert(h<=RAND_MAX);
  18. return rand()%h;
  19. }
  20.  
  21.  
  22. //rolls a virtual die
  23. //(die is the singular of dice)
  24. //returns a number 1-6
  25.  
  26. int rolldie(){
  27. return rnd(6)+1;
  28. }
  29.  
  30.  
  31. //flips a virtual coin
  32. //returns 1 or 0 for heads or tails
  33.  
  34. int flipcoin(){
  35. return rand()&1;
  36. }
  37.  
  38.  
  39.  
  40. //returns a floating point number in range 0 to 1
  41.  
  42. double frand(){
  43. return rand()/((double)RAND_MAX+1);
  44. }
  45.  
  46.  
  47. //returns random floating point number in range 0 to f
  48.  
  49. double frnd(float f){
  50. return frand()*f;
  51. }
  52.  
  53.  
  54. //returns 1 (true) at probability p
  55. //example:
  56. //prob(0.7) will be true 70% of the time
  57.  
  58. int prob(float p){
  59. if(frand()<p)return 1;
  60. return 0;
  61. }
  62.  
  63.  
  64.  
  65. //returns distance between two points in 2 dimensions
  66.  
  67. double dist2d(float x1,float y1,float x2,float y2){
  68. float dx=x1-x2;
  69. float dy=y1-y2;
  70. return sqrt(dx*dx+dy*dy);
  71. }
  72.  
  73.  
  74. //returns distance between two points in 3 dimensions
  75.  
  76. double dist3d(float x1,float y1,float z1,float x2,float y2,float z2){
  77. float dx=x1-x2;
  78. float dy=y1-y2;
  79. float dz=z1-z2;
  80. return sqrt(dx*dx+dy*dy+dz*dz);
  81. }
  82.  
  83.  
  84.  
  85. //Like % (modulus) but works "correctly" for negative values
  86.  
  87. signed int zmod(signed int a,unsigned int b){
  88. signed int c=0;
  89. if(!b)return c;//making sure we don't divide by zero
  90. if(a<0)--a;
  91. c=a%b;
  92. return c;
  93. }
  94.  
  95.  
  96. //returns volume of sphere having radius r
  97. //the parentheses may help compiler optimize
  98.  
  99. double spherevolume(float r){
  100. return (M_PI*4/3)*(r*r*r);
  101. }
  102.  
  103.  
  104. //returns surface area of sphere having radius r
  105.  
  106. double spheresurface(float r){
  107. return (M_PI*4)*(r*r);
  108. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.