BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

C++ Tutorial - Random Numbers

cplusplus_icon.png




Bookmark and Share





bogotobogo.com site search:




Randomness and Random number

Dilbert_random.gif

Source: Dilbert


What's randomness?


What's the difference between pseudo random number and real random number?
Here is a site all about RNADOM: http://www.random.org/randomness/.



Random number in C++

Through out this page, we're limited to pseudo-random numbers.

We can generate a pseudo-random number in the range from 0.0 to 32,767 using rand() function from <cstdlib> library. The maximum value is library-dependent, but is guaranteed to be at least 32767 on any standard library implementation. We can check it from RAND_MAX:

cout << "RAND_MAX=" << RAND_MAX << endl;    // RAND_MAX=32767

We can set the range of generated numbers using % (modulus) operator by specifying a maximum value. For instance, to generate a whole number within the range of 1 to 100:

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
	int i = 0;
	while(i++ < 10) {
		int r = (rand() % 100) + 1;
		cout << r << " ";
	}
	return 0;
}

Smaple output:

42 68 35 1 70 25 79 59 63 65

However, the numbers generated by the rand() are not random because it generates the same sequence each time the code executed. So, if we run the code again, we'll get the same sequence repeated as in the previous run.

To make a different sequence of numbers, we should specify a seed as an argument to a srand() function:

srand(98765);

We will get the diffent sequence of numbers by using the srand(), however, the sequence will still be repeated each time the code is executed. To generate a ever changing sequence, we need to feed something other than static integer to the argument of the srand() function.

The best solution is to seed the rand(0 function using the current time as the argument to srand(), by calling time() function from the standard C++ library, <ctime>. This returns the time as the type of time_t. Then, for portability, we cast as an integer type:

srand((int) time(0));

The time() function returns the number of seconds since 00:00 hours, Jan 1, 1970 UTC (i.e., the current unix timestamp). This ensures the number generated by rand() will now seems to be truly random unless it is called again within the same second.

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
	srand((int)time(0));
	int i = 0;
	while(i++ < 10) {
		int r = (rand() % 100) + 1;
		cout << r << " ";
	}
	return 0;
}

If we run the code several times, we get different number sequences.

1st run:
8 5 1 35 88 68 20 86 48 29
next run:
13 6 98 29 74 51 14 49 31 99




Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






C++ Tutorials

C++ Home

Algorithms & Data Structures in C++ ...

Application (UI) - using Windows Forms (Visual Studio 2013/2012)

auto_ptr

Binary Tree Example Code

Blackjack with Qt

Boost - shared_ptr, weak_ptr, mpl, lambda, etc.

Boost.Asio (Socket Programming - Asynchronous TCP/IP)...

Classes and Structs

Constructor

C++11(C++0x): rvalue references, move constructor, and lambda, etc.

C++ API Testing

C++ Keywords - const, volatile, etc.

Debugging Crash & Memory Leak

Design Patterns in C++ ...

Dynamic Cast Operator

Eclipse CDT / JNI (Java Native Interface) / MinGW

Embedded Systems Programming I - Introduction

Embedded Systems Programming II - gcc ARM Toolchain and Simple Code on Ubuntu and Fedora

Embedded Systems Programming III - Eclipse CDT Plugin for gcc ARM Toolchain

Exceptions

Friend Functions and Friend Classes

fstream: input & output

Function Overloading

Functors (Function Objects) I - Introduction

Functors (Function Objects) II - Converting function to functor

Functors (Function Objects) - General



Git and GitHub Express...

GTest (Google Unit Test) with Visual Studio 2012

Inheritance & Virtual Inheritance (multiple inheritance)

Libraries - Static, Shared (Dynamic)

Linked List Basics

Linked List Examples

make & CMake

make (gnu)

Memory Allocation

Multi-Threaded Programming - Terminology - Semaphore, Mutex, Priority Inversion etc.

Multi-Threaded Programming II - Native Thread for Win32 (A)

Multi-Threaded Programming II - Native Thread for Win32 (B)

Multi-Threaded Programming II - Native Thread for Win32 (C)

Multi-Threaded Programming II - C++ Thread for Win32

Multi-Threaded Programming III - C/C++ Class Thread for Pthreads

MultiThreading/Parallel Programming - IPC

Multi-Threaded Programming with C++11 Part A (start, join(), detach(), and ownership)

Multi-Threaded Programming with C++11 Part B (Sharing Data - mutex, and race conditions, and deadlock)

Multithread Debugging

Object Returning

Object Slicing and Virtual Table

OpenCV with C++

Operator Overloading I

Operator Overloading II - self assignment

Pass by Value vs. Pass by Reference

Pointers

Pointers II - void pointers & arrays

Pointers III - pointer to function & multi-dimensional arrays

Preprocessor - Macro

Private Inheritance

Python & C++ with SIP

(Pseudo)-random numbers in C++

References for Built-in Types

Socket - Server & Client

Socket - Server & Client 2

Socket - Server & Client 3

Socket - Server & Client with Qt (Asynchronous / Multithreading / ThreadPool etc.)

Stack Unwinding

Standard Template Library (STL) I - Vector & List

Standard Template Library (STL) II - Maps

Standard Template Library (STL) II - unordered_map

Standard Template Library (STL) II - Sets

Standard Template Library (STL) III - Iterators

Standard Template Library (STL) IV - Algorithms

Standard Template Library (STL) V - Function Objects

Static Variables and Static Class Members

String

String II - sstream etc.

Taste of Assembly

Templates

Template Specialization

Template Specialization - Traits

Template Implementation & Compiler (.h or .cpp?)

The this Pointer

Type Cast Operators

Upcasting and Downcasting

Virtual Destructor & boost::shared_ptr

Virtual Functions



Programming Questions and Solutions ↓

Strings and Arrays

Linked List

Recursion

Bit Manipulation

Small Programs (string, memory functions etc.)

Math & Probability

Multithreading

140 Questions by Google



Qt 5 EXPRESS...

Win32 DLL ...

Articles On C++

What's new in C++11...

C++11 Threads EXPRESS...

Go Tutorial

OpenCV...








Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master