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
Release: 2023-03-31 06:48:01
Original
3498 people have browsed it

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

For example:

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

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;;
}?>
Copy after login

Output:

0.59804026251568
0.67772196544228
0.90589751205682
0.45087858822703
0.17475316774787
Copy after login

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template