Home >Backend Development >PHP Tutorial >How to generate random decimals from 0 to 1 through php

How to generate random decimals from 0 to 1 through php

jacklove
jackloveOriginal
2018-06-09 09:35:413530browse

Javascript's method of generating random decimals from 0 to 1 can call its own Math.random();

For example:

8019067d09615e43c7904885b5246f0adocument.write(Math.random()); // 0.58404986071400342cacc6d41bbb37262a98f745aa00fbf0

There is in php rand,mt_randrandom methods, but neither of these two methods can generate 0~1 random decimals. We can write a method to achieve this function.
The method for php to generate random decimals from 0 to 1 is as follows:

<?php/**
 * 生成0~1随机小数
 * @param  Int   $min
 * @param  Int   $max
 * @return Float
 */function randFloat($min=0, $max=1){
    return $min + mt_rand()/mt_getrandmax() * ($max-$min);
}// 例子,创建5个0~1随机小数for($i=0; $i<5; $i++){    echo randFloat().&#39;<br>&#39;;
}?>

Output:

0.59804026251568
0.67772196544228
0.90589751205682
0.45087858822703
0.17475316774787

Javascript generates 0 ~1 random decimal method can call the built-in Math.random();

For example:

<script type="text/javascript">document.write(Math.random()); // 0.5840498607140034</script>

This article explains how to generate 0~1 random decimal through php , for more related content, pay attention to the php Chinese website.

Related recommendations:

About the usage instructions of the mysql timestamp formatting function from_unixtime

About the mysql functions concat and group_concat Instructions for use

Explanation on how to handle the problem that mysql innodb fails to start and cannot be restarted

The above is the detailed content of How to generate random decimals from 0 to 1 through php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn