Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random float between two floats

Tags:

c++

random

I know this is a rather simple question, but I'm just not too good at maths.

I know how to generate a random float between 0 and 1:

float random = ((float) rand()) / (float) RAND_MAX; 
  • But what, if I want a function that given a range of two floats, returns a pseudorandom float in that range?

Example:

RandomFloat( 0.78, 4.5 ); //Could return 2.4124, 0.99, 4.1, etc. 
like image 653
Maks Avatar asked Mar 13 '11 13:03

Maks


People also ask

How do you generate multiple random floats in Python?

Syntax. The random. uniform() function returns a random floating-point number N such that start <= N <= stop . In simple words, uniform(10.5, 15.5) will generate any float number greater than or equal to 10.5 and less than or equal to 20.5.

How do you generate a random float number between a specific range in Python?

In Python, the random. uniform() function gives a random floating-point number, and that is within a specified range. For example, it can produce a random float number in the range of 10 to 100. From 50.50 to 75.5, as an alternative.

How do you generate a random float in Python?

To get a random floating number we will use random. uniform() function this will give a float number between a given range. We can also round these floating numbers using the round() function in Python.


1 Answers

float RandomFloat(float a, float b) {     float random = ((float) rand()) / (float) RAND_MAX;     float diff = b - a;     float r = random * diff;     return a + r; } 

This works by returning a plus something, where something is between 0 and b-a which makes the end result lie in between a and b.

like image 92
Wim Avatar answered Sep 21 '22 02:09

Wim