Hey, what's going on?

Archive for March, 2018

Floating point (decimal) random numbers between two values in C++

Posted by Syeilendra Pramuditya on March 1, 2018

/* Floating point (decimal) random numbers between two values in C++
   Generate decimal random numbers between lim1 and lim2
   Created   : 1 March 2018
   Programmer: Syeilendra Pramuditya 
   URL       : https://wp.me/p61TQ-17R */
   
#include <iostream>
#include <cmath>
#include <ctime>
using namespace std;

int main(){
int i,rand_int,imax;
double sum,avrg_num,avrg_exc,rand_float,lim1,lim2;

srand (time(NULL)); //random seed

lim1 = 3.2; //lower limit
lim2 = 5.7; //upper limit

sum=0;
imax=100; //number of sampling
for(i=1;i<=imax;i++){
rand_int = rand();
rand_float = lim1+(lim2-lim1)*float(rand_int)/RAND_MAX;
sum = sum + rand_float;
cout << "Random number = "<<rand_float<<"\n";	
}
avrg_exc = 0.5*(lim1 + lim2);
avrg_num = sum/imax;
cout << "\nAvrg value, exact = "<<avrg_exc<<"\n";
cout << "Avrg value, numeric = "<<avrg_num<<"\n";
cout << "Max value = "<<RAND_MAX<<"\n\n";
return 0;
}

Posted in programming | Leave a Comment »