Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP random decimal between two decimals with step 0.5

Tags:

php

random

I want to create random number between two decimal numbers with step 0.5.

Examples: 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, ...

Use PHP To Generate Random Decimal Beteween Two Decimals

So far I can generate numbers between 0 and 5 with one decimal comma.

How to integrate step 0.5?

$min = 0;
$max = 5;
$number = mt_rand ($min * 10, $max * 10) / 10;
like image 782
Ing. Michal Hudak Avatar asked Jan 13 '15 21:01

Ing. Michal Hudak


People also ask

How can I generate a random number between two numbers in PHP?

The rand() function generates a random integer. Example tip: If you want a random integer between 10 and 100 (inclusive), use rand (10,100). Tip: As of PHP 7.1, the rand() function has been an alias of the mt_rand() function.

How do you generate random decimal numbers?

Generate a random decimal within a specified rangeEnter the formula =RAND()*([UpperLimit]-[LowerLimit])+[LowerLimit]. For example, if you'd like to generate a random decimal between one and 10, you may enter =RAND()*(10-1)+1. Press the "Enter" key.

What is mt_ rand in PHP?

Definition and Usage. The mt_rand() function generates a random integer using the Mersenne Twister algorithm. Example tip: If you want a random integer between 10 and 100 (inclusive), use mt_rand (10,100).

How do you generate a random decimal number in Python?

Use a random. random() function of a random module to generate a random float number uniformly in the semi-open range [0.0, 1.0) . Note: A random() function can only provide float numbers between 0.1. to 1.0. Us uniform() method to generate a random float number between any two numbers.


2 Answers

This should work for you:

$min = 0;
$max = 5;
echo $number = mt_rand($min * 2, $max * 2) / 2;
like image 124
Rizier123 Avatar answered Sep 22 '22 11:09

Rizier123


Another possible way:

function decimalRand($iMin, $iMax, $fSteps = 0.5)
{
    $a = range($iMin, $iMax, $fSteps);

    return $a[mt_rand(0, count($a)-1)];
}
like image 29
Raisch Avatar answered Sep 26 '22 11:09

Raisch