3

I am attempting Monte Carlo integration for an assignment. This involves generating random numbers between -1 and 1 in both the x and y axis... I think I know how to generate random nmumbers between 0 and 1, but don't know how to change that to between -1 and 1. Any help would be appreciated and thanks in advance... Here's (a bit of) my code so far:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

double x,y;


int main(){

srand(time(NULL));

x=rand()/(double)(RAND_MAX);
y=rand()/(double)(RAND_MAX); /*HOW DO I MAKE THIS FROM -1 TO 1*/

return 0;
}

*I'm pretty sure I can tackle the rest of the problem myself once I know how to generate these negative random numbers so the code above is only a small section of the problem (the rest I intend to do myself)

tshepang
  • 12,111
  • 21
  • 91
  • 136
user3368326
  • 51
  • 1
  • 3

3 Answers3

5
double randf(double low,double high){
    return (rand()/(double)(RAND_MAX))*abs(low-high)+low;
}

randf(-1,1);
SteveL
  • 3,331
  • 4
  • 32
  • 57
  • Elegant code, but why use `float`? `double` would be better. – Yu Hao Mar 01 '14 at 14:14
  • @yu Depends on why you need it , I usually use floats cause I don't need the accuracy of doubles and memory use is important.In most of the problems double is not necessary ,floats have enough accuracy. – SteveL Mar 01 '14 at 14:29
  • I don't think memory use is important in this function judging by its purpose. And that's almost the only advantage of `float` over `double`. Plus, the parameters and result in the OP's code is using `double`, using `float `would requite additional cast. – Yu Hao Mar 01 '14 at 14:35
  • You are right,in this case it doesn't matter ,its just a habit of mine to always use floats :) ,I changed it. – SteveL Mar 01 '14 at 14:37
4

Can't you just do x=(rand()/(double)(RAND_MAX)) * 2 - 1 ?

wennho
  • 123
  • 1
  • 7
1

Here you go...

y=rand() % 3 - 1;

the "% 3" will make it all the results are between 0 and 2.

and the -1 will decrease it so the lowest number can be -1.

example:

if you get a number 2 from the mod, the -1 will make it 1.

if you get a number 1 from the mod, the -1 will make it 0.

if you get a number 0 from the mod, the -1 will make it -1. :)

NULL
  • 31
  • 1
  • 1
  • 6